JavaScript“新数组(n)"和“Array.prototype.map"怪异

编程入门 行业动态 更新时间:2024-10-25 18:33:06
本文介绍了JavaScript“新数组(n)"和“Array.prototype.map"怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 06:48:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/881949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   怪异   quot   JavaScript   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!