【发布时间】:2017-03-29 20:30:51
【问题描述】:
考虑我声明两个这样的变量(在 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'
那么为什么会有差异呢?
【问题讨论】:
-
Object.keys(x)vsObject.keys(y)绝对是原因。 -
我从来没有想过要在数组中查找键(鉴于 isArray() 如何返回 true)!
标签: javascript node.js