- 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(previousValue, currentValue){}) : 遍历累加返回一个最终结果
var result = arr.reduce(function (previousValue, currentValue, currentIndex, array) {
/*
previousValue: 上一次函数的返回值。默认是reduce的第二个参数
currentValue: 当前遍历数组元素的值
currentIndex: 当前遍历数组元素的下标 (可选)
array: 数组本身 (可选)
*/
return previousValue + currentValue;
}, 0);
//用箭头函数写
[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );
7.Array.prototype.slice(begin,end) 返回一个新的数组对象,(包括 begin,不包括end)。原始数组不会被改变
//begin可选,如果省略 索引 0 开始。
//end可选
['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'].slice(1, 3);
// vue中常用slice将伪数组变为真数组
Array.prototype.slice.call(arguments)
8.Array.prototype.splice(start,deleteCount,item1, item2, …) 通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
//deleteCount,可选 整数,表示要移除的数组元素的个数。
//item1, item2, ...可选 要添加进数组的元素从start 位置开始。
//1.添加元素:从索引为2的位置开始添加元素 "drum"
["angel", "clown", "mandarin", "sturgeon"].splice(2, 0, "drum");
//2.删除元素:从索引为2的位置开始删除2个元素
["angel", "clown", "mandarin", "sturgeon"].splice(2, 2);
//3.删除并添加元素:从索引为2的位置开始删除1个元素并添加2个元素
["angel", "clown", "mandarin", "sturgeon"].splice(2, 1, "drum", "sturgeon");
9.Array.prototype.some(function(element, index, array) {}) index,array 可选
测试数组中是不是至少有1个元素满足条件。它返回true或false
[2, 5, 8, 1, 4].some(x => x > 10); // false