问题:Array.from()与Array.reduce()的使用
1、ES6中的 Array.from() 方法
Array.from方法用于将两类对象转为真正的数组:
类数组的对象(array-like object) 和 可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。
下面是一个类数组的对象,Array.from将它转为真正的数组:
let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; // ES5的写法 var arr1 = [ ].slice.call(arrayLike); // ['a', 'b', 'c'] // ES6的写法 let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
实际应用中,常见的类似数组的对象是 DOM 操作返回的 NodeList 集合,以及函数内部的arguments对象。Array.from都可以将它们转为真正的数组。
/ NodeList对象 let ps = document.querySelectorAll('p'); Array.from(ps).filter(p => { return p.textContent.length > 100; }); // arguments对象 function foo() { var args = Array.from(arguments); // ... }
上面代码中,querySelectorAll方法返回的是一个类似数组的对象,可以将这个对象转为真正的数组,再使用filter方法。
2、ES5中的 Array.reduce() 方法
reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。
使用示例:
示例一:
var total = [0, 1, 2, 3].reduce(function(a, b) { return a + b; }); console.log(total); // 6
示例二:
var total = [0, 1, 2, 3].reduce(function(a, b) { return a + b; },10); console.log(total); // 16
示例三:数组扁平化
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b); }); // flattened is [0, 1, 2, 3, 4, 5]