js的简单算法
求和
var array = [3,3,4,5,7,89,0,-10];
console.log(array)
//求和
var sum = 0;
for(const value of array){
sum += value;
}
console.log("求和:",sum)
求最大最小值
//最大 、最小值
var array = [3,3,4,5,7,89,0,-10];
var max=min=array[0];
for(const index in array){
if(max <= array[index]){
max = array[index];
}else{
min = array[index]
}
}
console.log("MAX:",max)
console.log("MIN:",min)
排序-冒泡排序
var array = [3,3,4,5,7,89,0,-10];
var temp = 0;
for(var i = 0;i<array.length-1;i++){
for(var j = 0;j<array.length-1-i;j++){
if(array[j] > array[j+1]){
temp = array[j];
array[j]= array[j+1];
array[j+1] = temp;
}
}
}
console.log("从小到大排序:",array);
数组去重
var array = [3,3,4,5,7,89,0,-10];
var arr = [3,3,4,5,7,89,0,-10];
var newArr = [arr[0]];
for(var i =1 ;i<arr.length;i++){
var repeat = false;
for(var j=0;j<newArr.length;j++){
if(newArr[j] == arr[i]){
repeat = true;
break;
}
}
if(!repeat){
newArr[newArr.length] = arr[i];
}
}
console.log("去重后",newArr);