ES5中常用的Array扩展方法
- ES5中常用的Array扩展方法
- Array.prototype.indexof(value);
- Array.prototype.lastindexof(value);
- Array.prototype.foreach(function(item,index){});
- Array.prototype.map(function(item,index){});
- Array.prototype.filter(function(item,index){});
- Array.prototype.reduce(function(total,currentValue,currentIndex,array){});
- Array.prototype.reduceRight(function(total,currentValue,currentIndex,array){});
Array.prototype 可以理解为Array实例
ES5中常用的Array扩展方法
var arr=[2,5,6,9,1,3,8,3,1,6];
Array.prototype.indexof(value);
得到值在数组的第一个下标
console.log(arr.indexOf(6)); //2
Array.prototype.lastindexof(value);
得到值在数组的最后一个下标
console.log(arr.lastIndexOf(6)) //9
Array.prototype.foreach(function(item,index){});
遍历数组
arr.forEach(function(item,index){
console.log("当前元素:"+item+",当前索引:"+index);
})
Array.prototype.map(function(item,index){});
遍历数组返回加工之后的一个新数组
var arrMap=arr.map(function(item,index){
return item+10;
})
console.log(arrMap);
Array.prototype.filter(function(item,index){});
遍历过滤出一个新的子数组,返回条件为true得值
//产生一个新数组,要求每个元素都大于3
var arrFilter=arr.filter(function(item,index){
return item>3;
})
console.log(arrFilter);
Array.prototype.reduce(function(total,currentValue,currentIndex,array){});
接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。[对于空数组是不会执行回调函数的]
-
total
- 初始值, 或者计算结束后的返回值 currentValue
- 当前元素的值 currentIndex
- 当前元素的索引 array
- 当前元素所属的数组对象。
//计算数组中所有数的总和
var sum=arr.reduce(function(total,currentValue,currentIndex,array){
console.log("初始值, 或者计算结束后的返回值。:"+total,",当前元素:"+currentValue,",当前元素的索引:"+currentIndex,",当前元素所属的数组对象。:"+array);
return total+currentValue;
});
console.log(sum); //44
Array.prototype.reduceRight(function(total,currentValue,currentIndex,array){});
Array.prototype.reduceRight()方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。