ES5新增的遍历数组的7种方法
1.indexOf和LastIindexOf
indexOf是从前到后查找数组元素出现的第一个位置;lastIndexOf函数从后前查找数组元素出现的第一个位置。
var a = [1,2,3,3,2,1]
console.log(a.indexOf(2)) //1
console.log(a.lastIndexOf(2)) //4
2.forEach
var arr = [1, 2, 3, 4, 5, 6, 7]
arr.forEach(function (item, index, arr) {
arr[index] = item + 1
});
console.log(arr); //[2, 3, 4, 5, 6, 7,8]
3.map
与forEach类似,遍历数组,返回值组成一个新数组返回,新数组索引结构和原数组一致,原数组不变
var arr = [1, 2, 3, 4, 5, 6]
var newarr = arr.map(function (item, index, arr) {
return item * 2
})
console.log(newarr) //[2, 4, 6, 8, 10, 12]
4.every
判断数组中是否存在满足指定条件的数组元素,只有所有数组元素都满足指定条件才会返回true,只要有一个数组元素不满足条件都会返回false
var arr = [1, 2, 3, 4, 5, 6];
var newarr = arr.every(function (item, index, arr) {
return item > 5
})
console.log(newarr);//false
5.some
判断数组中是否存在满足指定条件的数组元素,只要有一个数组元素满足指定条件就返回true
var arr = [1, 2, 3, 4, 5, 6];
var newarr = arr.some(function (item, index, arr) {
return item > 5
})
console.log(newarr);//true
6.filter
筛选出满足指定条件的数组元素,并且返回由满足指定条件的数组元素组成的新数组
var arr = [1, 2, 3, 4, 5, 6];
var newarr = arr.filter(function (item, index, arr) {
return item > 5
})
console.log(newarr);//6
7. reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
var arr = [100, 200, 300, 400]
var newArr = arr.reduce(function(preval, item, index, arr) {
console.log(preval, item, index, arr)
return preval + item
})
console.log(newArr)