ekk*_*kis 7 javascript node.js
考虑我声明两个这样的变量(在REPL中完成,节点v7.7.2),我期望它是数组:
var x = Array(4)
var y = Array.from({length: 4})
Run Code Online (Sandbox Code Playgroud)
然后以下应该相同,但它不会:
x.map(Math.random)
[ , , , ]
y.map(Math.random)
[ 0.46597917021676816,
0.3348459056304458,
0.2913995519428412,
0.8683430009997699 ]
Run Code Online (Sandbox Code Playgroud)
在看,似乎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'
Run Code Online (Sandbox Code Playgroud)
为什么差异呢?
对于前三个输出,Array#map有效。
\n\n\n对于数组\xc2\xa0 中缺少\xc2\xa0 元素(即从未设置过的\xc2\xa0、已被删除或从未被赋值的索引),不会调用它。
\n
ECMA 262 标准Array.from描述了新数组的长度构造(第 7 点 ff)。
var x = Array(4),\r\n y = Array.from({ length: 4 }),\r\n arrayX = x.map(Math.random),\r\n arrayY = y.map(Math.random),\r\n z = Array.from({ length: 4 }, Math.random);\r\n\r\nconsole.log(x);\r\nconsole.log(y);\r\nconsole.log(arrayX);\r\nconsole.log(arrayY);\r\nconsole.log(z);Run Code Online (Sandbox Code Playgroud)\r\n| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |