es5 新增数组方法

1.浏览器支持情况:chrome8+、ff3.6+、IE9+

2.forEach遍历 [1, 2, 3, 4].forEach(function (item, index, arr) {console.log(item);});
支持3个参数:其中第一个参数代表数组内容,第二个参数是索引,第三个是数组本身.

除了第一必选的回调函数,还可接收一个可选参数来改变this指向。

3.map映射,将一个数组映射成为一个新的数组,回调函数的参数同forEach。
var a = [1, 2, 3, 4].map(function (item, index, arr) {return item*item;});
// a = [1, 4, 9, 16];
注意:写map最好写上返回值,这是正规写法。否则在正规带有eslint检查的项目中会报error。

4.filter过滤,此方法可批量删除已知索引的数组值。回调中需要过滤的返回false,通过的返回true
var deleteIndex = [0, 2];
var arr = [7, 8, 9, 10];
var filterArr = arr.filter(function (item, index) {return deleteIndex.indexOf(index) > -1 ? false : true;});
// filterArr [8, 10]

5.some某些项符合条件,只要有true,则不再返回执行。array.some(callback[, this]);返回boolean值。
[5, 6, 8].some(function(item){return item > 7;}); // true
[5, 6, 8].some(function(item){return item > 9;}); // false

6.every需要每一项都符合要求,返回boolean值。array.every(callback[, this]);
[5, 6, 8].every(function(item){return item > 7;}); // false
[5, 6, 8].every(function(item){return item > 4;}); // true

7.indexOf与字符串中的用法类似。返回索引值,如果没有严格匹配,则返回-1.其中index不需要严格匹配,传’1’也可以识别。
array.indexOf(searchElement[, fromIndex])
第二个参数表示从指定索引开始向后找。>=
[2, 3, 4].indexOf(3); // 1
[2, 3, 4].indexOf(5); // -1
2, 3, 4].indexOf(3, 2); // -1

8.lastIndexOf,用法与indexOf类似。从后往前找。
array.lastIndexOf(searchElement[, fromIndex])
fromIndex默认表示array.length - 1;
[2, 3, 10, 9, 4].lastIndexOf(9, 1); // -1(从后往前,从索引值为1的开始搜索)
[2, 3, 10, 9, 4].lastIndexOf(10, 3); // 2
[2, 3, 10, 9, 4].lastIndexOf(1); // -1

9.reduce递归,callback函数接受4个参数:之前值、当前值、索引值以及数组本身。参数解析:
因为initialValue不存在,因此一开始的previous值等于数组的第一个元素。
从而current值在第一次调用的时候就是2.
最后两个参数为索引值index以及数组本身array.
array.reduce(callback[, initialValue])
[[1, 2], [3, 4], [5, 6]].reduce(function(prev, current){console.log(prev, current); return prev.concat(current);}); // [1, 2, 3, 4, 5, 6]

10.reduceRight,与reduce用法类似,但是从数组末尾开始。
array.reduceRight(callback[, initialValue])
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

猜你喜欢

转载自blog.csdn.net/weixin_44713446/article/details/88945231