concat()
创建一个副本,返回新构建的数组
slice()
创建一个包含原有数组中一个或多个元素的新数组
reduce()
reduce()方法不会改变原有数组
filter
将所有元素进行判断,将满足条件的元素作为一个新的数组返回
some
将所有元素进行判断返回一个布尔值,如果存在元素都满足判断条件,则返回true,若所有元素都不满足判断条
件,则返回false;
every
将所有元素进行判断返回一个布尔值,如果所有元素都满足判断条件,则返回ue,否则为false;
求最大值
1 2
| vara=[1,2,3,4]; Math.max.apply(null,a);
|
join
纯函数
flat(),flatMap()
将数组扁平化处理,返回一个新数组,对原数据没有影响。
flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平
的层数,默认为1。
flatMap()方法对原数组的每个成员执行一个函数相当于执行Array.prototype.map(),然后对返回值组成的数组执行
flat()方法。该方法返回一个新数组,不改变原数组。
flatMap()方法还可以有第二个参数,用来绑定遍历函数里面的this。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| const nestedArray = [1, [2, [3, [4]], 5]];
const flatArrayOneLevel = nestedArray.flat(); console.log('flat() 一层拉平:', flatArrayOneLevel);
const flatArrayTwoLevels = nestedArray.flat(2); console.log('flat() 两层拉平:', flatArrayTwoLevels);
const flatArrayAllLevels = nestedArray.flat(Infinity); console.log('flat() 所有层拉平:', flatArrayAllLevels);
const flatMapArray = nestedArray.flatMap((item) => { return Array.isArray(item) ? item : [item]; }); console.log('flatMap():', flatMapArray);
const context = { multiplier: 10 }; const flatMapArrayWithContext = nestedArray.flatMap(function(item) { return Array.isArray(item) ? item.map(num => this.multiplier * num) : [this.multiplier * item]; }, context); console.log('flatMap() 绑定 this:', flatMapArrayWithContext);
|