Array.from() 与传播语法 [英] Array.from() vs spread syntax
问题描述
使用 Array.from(document.querySelectorAll('div'))
或 [...document.querySelectorAll('div')]
有什么区别吗?
Is there some difference between using Array.from(document.querySelectorAll('div'))
or [...document.querySelectorAll('div')]
?
这是一个例子:
let spreadDivArray = [...document.querySelectorAll('div')];
console.log(spreadDivArray);
let divArrayFrom = Array.from(document.querySelectorAll('div'));
console.log(divArrayFrom);
console.log()
将记录相同的结果.
有什么性能差异吗?
推荐答案
Spread element (它不是一个运算符) 仅适用于iterable(即实现@@iterator
方法).Array.from()
也适用于不可迭代的类数组对象(即具有 length
属性和索引元素的对象).看这个例子:
Spread element (it's not an operator) works only with objects that are iterable (i.e. implement the @@iterator
method). Array.from()
works also on array-like objects (i.e. objects that have the length
property and indexed elements) which are not iterable. See this example:
const arrayLikeObject = { 0: 'a', 1: 'b', length: 2 };
// This logs ['a', 'b']
console.log(Array.from(arrayLikeObject));
// This throws TypeError: arrayLikeObject[Symbol.iterator] is not a function
console.log([...arrayLikeObject]);
另外,如果你只是想将一些东西转换成数组,我认为最好使用 Array.from()
因为它更具可读性.例如,当您想要连接多个数组 (['a', 'b', ...someArray, ...someOtherArray]
) 时,展开元素很有用.
Also, if you just want to convert something to array, I think it's better to use Array.from()
because it's more readable. Spread elements are useful for example when you want to concatenate multiple arrays (['a', 'b', ...someArray, ...someOtherArray]
).
这篇关于Array.from() 与传播语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!