ES6
中Array
有两个新方法,Array.of()
和Array.from()
。在这个 page 中提到了它们的不同用法.
但是,我对 Array.of
在 line 中的用法感到困惑
// usage of Array.of
console.log(
Array.of( "things", "that", "aren't", "currently", "an", "array" )
); // ["things", "that", "aren't", "currently", "an", "array"]
如果我们像下面那样做呢
console.log(
[ "things", "that", "aren't", "currently", "an", "array" ]
); // ["things", "that", "aren't", "currently", "an", "array"]
我们可以获得与 console.log(Array.of(...))
相同的结果。在这里使用 Array.of
有什么好处吗?
也与此 line 中 Array.from
的用法混淆
var divs = document.querySelectorAll("div");
console.log(
Array.from( divs )
);
如果上面的代码中没有Array.from
怎么办
var arr = [1, 2, 3];
console.log(Array.from(arr)); // [1, 2, 3]
console.log(arr); // [1, 2, 3]
在这里使用 Array.from
有什么好处吗?
最佳答案
Array.of()
Brendan eich 说 ( Source ):
Dmitry A. Soshnikov wrote:
Brendan Eich wrote:
So the goal of Array.of is to provide a constructor that, unlike Array, does not have that insane special case for Array(42), which presets length (and hints to implementations to preallocate) but leaves holes in [0, length).
我仍然不明白它对手动枚举相同的内容有何帮助 可以直接传递给数组初始化程序的括号的项目。 我们在这里(手工)枚举项目,对吗? --
Array.of(1, 2, 3)
。和 我们在这里枚举项目(也用手)——[1, 2, 3]
。区别 是第二种情况在句法上更优雅和甜美 也不需要通过分配激活不需要的功能 调用堆栈框架等这都是真的,但跑题了。用例是当你不能 写一个文字,因为你正在传递一个构造为的函数 一个 funarg,最终的调用者可能只传递一个数字 arg,或者 几个参数。在这种情况下,Array 将不会做正确的事情 一个参数大小写。
这就是
Array.of
的原因。
例子:
// Array.of(42) creates an array with a single element, 42, whereas Array(42) creates an array with 42 elements, each of which is undefined.
console.log(new Array(42));
console.log(Array.of(42));
Array.from()
Array.from()
方法从一个类数组或可迭代对象创建一个新的 Array 实例。
- 类数组对象(具有长度属性和索引元素的对象)
- 可迭代对象(您可以从中获取其元素的对象,例如 Map 和 Set)。
例如:
var m = new Map([[1, 2], [2, 4], [4, 8]]);
console.log("m is:");
console.log(m);
var _from = Array.from(m);
console.log("After .from: ");
console.log(_from);
关于javascript - Array.of() 和 Array.from() 的奇怪用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34759831/