Array indexing problem

A

Antti Nummiaho

Consider the following javascript:

var temp = new Array(new Array(0))
document.writeln(temp[0][0])

temp = new Array(new Array(0,1))
document.writeln(temp[0][0])

One would assume that it would print "0 0" that is the first elements
of the arrays, but it prints "undefined 0". Why does temp[0][0] return
undefined when there is only one element in the array but returns the
first element correctly when there are at least two elements?
 
T

Thomas 'PointedEars' Lahn

to said:
Consider the following javascript:

var temp = new Array(new Array(0))
document.writeln(temp[0][0])

temp = new Array(new Array(0,1))
document.writeln(temp[0][0])

One would assume that it would print "0 0" that is the first elements
of the arrays, but it prints "undefined 0". Why does temp[0][0] return
undefined when there is only one element in the array but returns the
first element correctly when there are at least two elements?

That is because the behaviour of the Array object is different
when you pass two or more integers to the Array constructor.

If you pass one integer to the Array constructor it will create
an Array of that size. If you pass two or more integers it will
use them as elements in the array.

More, how it is interpreted depends on the implementation. To be
sure, use Array literals:

var temp = [[0]];

creates an Array object with an Array object as only element which
only element is zero and stores a reference to it in `temp'. The
"same" can be accomplished with leaving out constructor arguments,
but requiring another variable:

var help = new Array();
help[0] = 0;
var temp = new Array(help);

Note that although temp[0][0] retrieves `0', deleting or overwriting
`help[0]' changes that value since the reference is stored as element,
not the primitive value of zero:

help[0] = 42;
alert(temp.join(",")); // 42


PointedEars

P.S.
Your `From' is borken, read and follow
<http://www.interhack.net/pubs/munging-harmful/>
if you want to be read in the future.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top