1. 介绍
JavaScript 中有一个这样的函数: Array.from:允许在 JavaScript 集合(如:
数组、类数组对象、或者是字符串、map 、set 等可迭代对象) 上进行有用的转换。
Array.from(arrayLike,mapFn,thisArg)
参数
arrayLike
:想要转换为数组的伪数组对象或可迭代对象。mapFn
:可选,如果指定了该参数 新数组中的每一个元素会执行该回调函数。mapFn(item,index){…}是在集合中的每个项目上调用的函数。返回的值将插入到新集合中。thisArg
:可选,执行回调函数mapFn时this对象,这个参数很少用到。
Array.from() 方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
返回值: 一个新的数组实例。
2. 将类数组对象转换为数组
南栀的博客—数组、对象、类数组对象
通常,你会碰到的类数组对象有:函数中的 arguments 关键字,或者是一个 DOM 集合。
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
3. 从String生成数组
Array.from('foo');
// [ "f", "o", "o" ]
4. 从Set生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
5. 从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']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
6. 克隆一个数组
const numbers = [3, 6, 9];
const numbersCopy = Array.from(numbers);
numbers === numbersCopy; // => false
- Array.from(numbers) 创建了对 numbers 数组的浅拷贝,numbers === numbersCopy 的结果是 false,意味着虽然 numbers 和 numbersCopy 有着相同的项,但是它们是不同的数组对象。
function recursiveClone(val) {
return Array.isArray(val) ? Array.from(val, recursiveClone) : val;
}
const numbers = [[0, 1, 2], ['one', 'two', 'three']];
const numbersClone = recursiveClone(numbers);
numbersClone; // => [[0, 1, 2], ['one', 'two', 'three']]
numbers[0] === numbersClone[0] // => false
- recursiveClone() 能够对数组的深拷贝,通过判断 数组的 item 是否是一个数组,如果是数组,就继续调用 recursiveClone() 来实现了对数组的深拷贝。