Array
中有两种新的ES6
方法,Array.of()
和Array.from()
。它们的区别用法在这个page中有提到。
但是,我对这
行中
Array.of
的用法感到困惑
// 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
有什么好处吗?
也对这
行中
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
有什么好处吗?
Brendan eich 说(来源):
德米特里·A·索什尼科夫写道:
布伦丹·艾奇写道:
因此 Array.of 的目标是提供一个构造函数,与 数组,没有 Array(42) 那种疯狂的特殊情况, 预设长度(以及预分配实现的提示)但是 在 [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实例。
例如:
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);
console.log(Array.of("Akansha")) //[ 'Akansha' ]
console.log(Array.from("Akansha")) //['A', 'k', 'a','n', 's', 'h','a']
让分数1 = 100
让分数2 = 200
让分数3 = 300
console.log(Array.of(score1,score2,score3)) //[ 100, 200, 300 ]