制造一个arrays – 为什么它不同?

考虑我声明这样的两个variables(在REPL中完成,节点v7.7.2),我期望它是数组:

var x = Array(4) var y = Array.from({length: 4}) 

那么以下应该同样工作,但它不:

 x.map(Math.random) [ , , , ] y.map(Math.random) [ 0.46597917021676816, 0.3348459056304458, 0.2913995519428412, 0.8683430009997699 ] 

在看,似乎x和y都是一样的:

 > typeof x 'object' > typeof y 'object' > Array.isArray(x) true > Array.isArray(y) true > x.length 4 > y.length 4 > typeof x[0] 'undefined' > typeof y[0] 'undefined' 

那么为什么不同?

对于前三个输出, Array#map起作用。

它不会被调用缺less的数组元素(也就是说,从来没有被设置过的索引,这些索引已经被删除,或者从来没有被赋值过)。

Array.from的ECMA 262标准描述了一个具有新arrays长度的构造(点Array.from )。

 var x = Array(4), y = Array.from({ length: 4 }), arrayX = x.map(Math.random), arrayY = y.map(Math.random), z = Array.from({ length: 4 }, Math.random); console.log(x); console.log(y); console.log(arrayX); console.log(arrayY); console.log(z); 

其实这两种情况都不应该有相同的结果。 在这里查看有关Array的手册:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

如果传递给Array构造函数的唯一参数是一个介于0和232-1(包含)之间的整数,则返回一个新的JavaScript数组,其长度属性设置为该数字( 注意:这意味着arrayLength空数组,而不是数组与实际的未定义值 )。 如果参数是任何其他数字,则会引发RangeErrorexception。

在这里关于Array.from()方法

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

检查上面链接的页面上的以下示例:

 // Generate a sequence of numbers // Since the array is initialized with `undefined` on each position, // the value of `v` below will be `undefined` Array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4] 

用Array(4)创build的数组不是用.map()迭代的,而Array.from({length:4})是迭代的​​。 一个更全面的解释可以在JavaScript“新Array(n)”和“Array.prototype.map”奇怪发现 ,你可以testing这..

 x.map((f,i) => console.log(i)) vs. y.map((f,i) => console.log(i))