Array.from()浅拷贝的数组实例

2019-09-073468次阅读javascriptES6

Array.from()从一个(如: 数组、类数组对象、或者是字符串、map 、set 等可迭代对象) 上创建一个新的,浅拷贝的数组实例。

Array.from(arrayLike[, mapFunction[, thisArg]])
  • arrayLike:必传参数,想要转换成数组的伪数组对象或可迭代对象。
  • mapFunction:可选参数,mapFunction(item,index){...}是在集合中的每个项目上调用的函数。返回的值将插入到新集合中。也就是说Array.from(obj, mapFn, thisArg)就相当于Array.from(obj).map(mapFn, thisArg)
  • thisArg:可选参数,执行回调函数mapFunction时 this 对象。这个参数很少使用。
const someNumbers = { '0': 10, '1': 15, length: 2 };
Array.from(someNumbers, value => value * 2); // => [20, 30]

 

将类数组对象转换成数组

类数组对象有:函数中的arguments关键字,或者是一个DOM集合。

function sumArguments() {
    return Array.from(arguments).reduce((sum, num) => sum + num);
}

sumArguments(1, 2, 3); // => 6

Array.from()的第一个参数可以是任意一个可迭代对象

Array.from('Hey');                   // => ['H', 'e', 'y']
Array.from(new Set(['one', 'two'])); // => ['one', 'two']

const map = new Map();
map.set('one', 1)
map.set('two', 2);
Array.from(map); // => [['one', 1], ['two', 2]]

 

克隆一个数组

const numbers = [3, 6, 9];
const numbersCopy = Array.from(numbers);
numbers === numbersCopy; // => false

Array.from(numbers)创建了对numbers数组的浅拷贝,numbers === numbersCopy的结果是false,意味着虽然numbers和numbersCopy有着相同的项,但是它们是不同的数组对象。

是否可以使用Array.from()创建数组的克隆?

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()来实现了对数组的深拷贝。

 

使用值填充数组

之前写过fill()方法给定一个数字快速的构造数组。其实使用Array.from()将是不错的选择。

const length = 3;
const init   = 0;
const result = Array.from({ length }, () => init);
result; // => [0, 0, 0]

值还可以是对象填充数组:

const length = 3;
const resultA = Array.from({ length }, () => ({}));
const resultB = Array(length).fill({});

resultA; // => [{}, {}, {}]
resultB; // => [{}, {}, {}]

resultA[0] === resultA[1]; // => false
resultB[0] === resultB[1]; // => true

由Array.from返回的resultA使用不同空对象实例进行初始化。之所以发生这种情况是因为每次调用时,mapFunction,即此处的() => ({})都会返回一个新的对象。

然后,fill()方法创建的resultB使用相同的空对象实例进行初始化。不会跳过空项。

 

生成数字范围

function range(end) {
    return Array.from({ length: end }, (_, index) => index);
}

range(4); // => [0, 1, 2, 3]

在range()函数中,Array.from()提供了类似数组的{length:end} ,以及一个简单地返回当前索引的map函数 。这样你就可以生成值范围。

 

上一篇: background-clip背景裁剪实现嵌套渐变背景  下一篇: URLSearchParams() API获取网址url查询参数  

Array.from()浅拷贝的数组实例相关文章