PDA

Click to See Complete Forum and Search --> : Arrays in Js


Vincent Puglia
Feb 14th, 2002, 04:50 PM
Hi,

if (myArray[3] == undefined) alert('hi')

Vinny

progressive
Feb 15th, 2002, 04:49 AM
??

what if he has 5 elements in his array eg a myArray[4] element

myArray[3] will be defined but wont contain a value wont it ???

if myArray[3] != null

usually works

Vincent Puglia
Feb 15th, 2002, 07:34 AM
Hi,

Because you have an array with cell[X], it doesn't mean you have to declare and define cell[X-1].

var myArray = new Array()
myArray[0] = 0;
myArray[1] = 1;
myArray[3] = 3;
myArray[4] = "";
myArray[5] = null;

With a normal for loop, the 'missing' cell will appear:

for (var i = 0 ; i < myArray.length; i++)
alert(myArray[i])

Whereas, with a 'for in' loop (which is usually used with associative arrays), it does not:

for (var i in myArray) alert(myArray[i])

As you said, 'null' works the same as 'undefined' -- to a point:

for (i = 0 ; i < myArray.length; i++)
if (myArray[i] != null) alert(myArray[i])

for (i = 0 ; i < myArray.length; i++)
if (myArray[i] != undefined) alert(myArray[i])

Also note that neither of the above catches an empty string ("")

for (i = 0 ; i < myArray.length; i++)
if (myArray[i] != "") alert(myArray[i])

Which ultimately means: null, undefined, and "" are 3 distinct values.

Vinny