Array.from()方法从一个类似数组或者可迭代的对象创建一个新的,浅拷贝的数组实例。
语法:
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike:想要转换成数组的类数组对象或可迭代对象。
mapFn:(可选)如果指定了该回调函数,则新数组中的每个元素都会执行该函数。
thisArg:(可选)执行回调函数时,指定的this的值。
返回值:一个新的数组实例。
描述:
Array.from() 可以通过以下方式创建新的数组
1.伪数组对象:拥有一个length属性和若干个索引属性的对象
2.可迭代对象:可以获取对象中的元素(如Map和Set等)
Array.from() 方法有一个可选参数 mapFn,相当于对新数组中的每一个元素都进行一次map操作然后再返回。实际上 Array.from(arrayLike, mapFn, thisArg)就相当于Array.from(arrayLike).map(mapFn, thisArg),除非创建的不是可用的中间数组。这对一些数组的子类如typed arrays来说很重要,因为中间数组的值在调用map时需要是适当的类型。
from()的length属性为1,即Array.from().length === 1;
示例
// 使用字符串生成数组
Array.from('abc'); // ['a', 'b', 'c']
// 使用Set生成数组
const set = new Set(['a', 'b', 'c', 'b', 'd', 'c', 'a']);
Array.from(set); // ["a", "b", "c", "d"]
// 使用Map生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map); // [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([[1, 'a'], [2, 'b'], [3, 'c']]);
Array.from(mapper.keys()); // [1, 2, 3]
Array.from(mapper.values()); // ['a', 'b', 'c']
// 从类数组对象(arguments)生成数组
function f() {
return Array.from(arguments);
}
f(1, 2, 3); // [1, 2, 3]
// 传入回调函数
const str = 'hello';
Array.from(str, x=>x.toUpperCase()); // ["H", "E", "L", "L", "O"]