The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flatten of depth 1, but flatMap is quite often useful and merging both into one method is slightly more efficient.
for example: we have an array arr = [0,1,2] , we have mapping function (x => [x, x+1]). we expect: arr.flatMap(x => [x, x+1]) = [0, 1, 1, 2, 2, 3]
数组的每个元素都使用给定的映射函数进行运算,最后将得出的结果压缩到一维数组中。数组的每个元素均用指定函数处理,可使用map方法处理,返回一个二维数组,最后将此数组降维。
Array.prototype.flatMap = function(f) { return [].concat.apply([],this.map(f))};
[1].flatMap(x => [x, x-1, x+2]), [1, 0, 3]
[0, 2].flatMap(x => [x, x, x]), [0, 0, 0, 2, 2, 2]
apply()方法:改变执行函数上下文,并传入数组参数
[].concat.apply([],this.map(f))
即空数组[]与this.map(f)返回的二维数组中所有元素(还是数组)进行拼接,[].concat.apply([],arr) 可以对二维数组进行降维操作。
对比call与apply,其实就是第二个参数的形式发生了变化。不需要传参或者只有1个参数的时候,用call
,当要传入多个对象时,用apply
此外,call常用来实现对象的继承。