Array.from()vs扩展语法 [英] Array.from() vs spread syntax

查看:109
本文介绍了Array.from()vs扩展语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Array.from(document.querySelectorAll('div')) [... document.querySelectorAll( 'div')]

这是一个例子:

let spreadDivArray = [...document.querySelectorAll('div')];
console.log(spreadDivArray);

let divArrayFrom = Array.from(document.querySelectorAll('div'));
console.log(divArrayFrom);

console.log()将记录相同的结果。

有没有性能差异?

推荐答案

嗯, Array.from 是一种静态方法,一个函数,而 spread 语法是数组文字语法的一部分。您可以传递类似数据的功能,您可以调用它们一次,多次或根本不调用。

Well, Array.from is a static method, i.e., a function whereas the spread syntax is part of the array literal syntax. You can pass functions around like data, you can invoke them once, several times or not at all. This isn't possible with the spread syntax, which is static in this regard.

另一个区别是,@ nils已经指出,这个 Array.from 也适用于类似数组的对象,它们不实现可迭代的协议。 spread 另一方面需要迭代。

Another difference, which @nils has already pointed out, is that Array.from also works with array-like objects, which don't implement the iterable protocol. spread on the other hand requires iterables.

这篇关于Array.from()vs扩展语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆