数组常用方法(都不改变原数组)
1. forEach(function (item,index,array){}) 遍历数组
var arr = [1,2,3,4,5,6];
arr.forEach(function(item,index){
console.log(item + ":" + index + ":" + array);
})
//1:0:1,2,3,4,5,6
//2:1:1,2,3,4,5,6
//3:2:1,2,3,4,5,6
//4:3:1,2,3,4,5,6
//5:4:1,2,3,4,5,6
//5:4:1,2,3,4,5,6
//复制数组
function fnCopyArr(arr){
var list = [];
arr.forEach(function (value){
list.push(value);
})
return list;
}
2. map(function (item,index,array){return ...}) 遍历数组,返回一个新数组
var arr = [1,2,3,4,5,6];
var list = arr.map(function(item){
return item + 5;
});
console.log(list); //[ 6, 7, 8, 9, 10, 11]
//复制数组
function fnCopyArr(arr){
var list = arr.map(function(value){
return value;
})
return list;
}
3. reduce(function(prev,next,index,array){ return...}) 归并
注:将prev与next中的值进行运算后,再次赋值给prev。
var arr = [1,2,3,4,5,6];
var sum = arr.reduce(function(prev,next){
return prev + next;
});
console.log(sum); //21
4. filter(function(item,index,array){return ...}) 过滤,返回数组
let peopleArr = this.drawArr.filter((item) => item.type === 'peopleImg');
var arr = [1,2,3,4,5,6];
var list = arr.filter(function(item){
return item > 3;
});
console.log(list); //[ 4, 5, 6 ]
var arr = [1,2,3,0,5,6];
var list = arr.filter(function(item){
return item >= 0;
});
console.log(list); //[ 1, 2, 3, 0, 5, 6 ]
5. indexOf(元素,开始下标) : 返回元素第一次出来的下标位置,如果没有找到,返回-1;
var arr = [1,2,3,2,5,2,6];
console.log(arr.indexOf(2,6)); //-1
console.log(arr.indexOf(2)); //1
6. lastIndexOf(元素,开始下标) 返回元素从右向左第一次出现的下标位置,如果没有找到,返回-1;