Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - JavaScript“ new Array(n)”和“ Array.prototype.map”怪异(JavaScript “new Array(n)” and “Array.prototype.map” weirdness)

I've observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2(我已经在Firefox-3.5.7 / Firebug-1.5.3和Firefox-3.6.16 / Firebug-1.6.2中观察到了这一点)

When I fire up Firebug:(当我启动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] 

What's going on here?(这里发生了什么?)

Is this a bug, or am I misunderstanding how to use new Array(3) ?(这是一个错误,还是我误会了如何使用new Array(3) ?)   ask by rampion translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It appears that the first example(看来第一个例子)

x = new Array(3);

Creates an array with undefined pointers.(用未定义的指针创建一个数组。)

And the second creates an array with pointers to 3 undefined objects, in this case the pointers them self are NOT undefined, only the objects they point to.(第二个对象创建一个带有指向3个未定义对象的指针的数组,在这种情况下,它们本身的指针不是未定义的,只有它们指向的对象才是未定义的。)

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

As map is run in the context of the objects in the array I believe the first map fails to run the function at all while the second manages to run.(由于map是在数组中对象的上下文中运行的,因此我相信第一个map根本无法运行该函数,而第二个map可以运行。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...