469,306 Members | 1,903 Online

# Array indexing problem

Consider the following javascript:

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

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

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 return
undefined when there is only one element in the array but returns the
first element correctly when there are at least two elements?

--
Antti
Jul 20 '05 #1
2 1435 >Consider the following javascript:

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

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

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 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.

var temp = new Array(new Array(0))

new Array( 0) creates an array of zero length.

temp = new Array(new Array(0,1))

new Array( 0,1) creates an array that contain [ 0, 1].

Peace, Vm
Yaz

Providing complicated solutions to simple problems since 1997.
Jul 20 '05 #2
to heave chunks wrote:
Consider the following javascript:

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

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

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 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 = [];

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;
var temp = new Array(help);

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

help = 42;
PointedEars

P.S.