JavaScript“新数组(n)"和“Array.prototype.map"怪异 [英] JavaScript "new Array(n)" and "Array.prototype.map" weirdness

查看:32
本文介绍了JavaScript“新数组(n)"和“Array.prototype.map"怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Firefox-3.5.7/Firebug-1.5.3 和 Firefox-3.6.16/Firebug-1.6.2 中观察到这一点

I've observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2

当我启动 Firebug 时:

When I fire up Firebug:

var x = new Array(3)
console.log(x) 
// [undefined, undefined, undefined]

var y = [undefined, undefined, undefined]
console.log(y) 
// [undefined, undefined, undefined]

console.log( x.constructor == y.constructor) // true

console.log( 
  x.map(function() { return 0; })
)
// [undefined, undefined, undefined]

console.log(
  y.map(function() { return 0; })
)
// [0, 0, 0]

这是怎么回事?这是一个错误,还是我误解了如何使用 new Array(3)?

What's going on here? Is this a bug, or am I misunderstanding how to use new Array(3)?

推荐答案

看来是第一个例子

x = new Array(3);

创建一个长度为 3 但没有任何元素的数组,因此不会创建索引 [0]、[1] 和 [2].

Creates an array with a length of 3 but without any elements, so the indices [0], [1] and [2] is not created.

第二个创建一个包含 3 个未定义对象的数组,在这种情况下,它们自己创建了索引/属性,但它们引用的对象未定义.

And the second creates an array with the 3 undefined objects, in this case the indices/properties them self are created but the objects they refer to are undefined.

y = [undefined, undefined, undefined]
// The following is not equivalent to the above, it's the same as new Array(3)
y = [,,,];

由于 map 在索引/属性列表上运行,而不是在设置的长度上运行,因此如果没有创建索引/属性,它将不会运行.

As map runs on the list of indices/properties, not on the set length, so if no indices/properties is created, it will not run.

这篇关于JavaScript“新数组(n)"和“Array.prototype.map"怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆