Results 1 to 3 of 3

Thread: Arrays in Js

  1. #1

    Thread Starter
    Member Vincent Puglia's Avatar
    Join Date
    Feb 2002
    Location
    where the World once stood
    Posts
    36
    Hi,

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

    Vinny

  2. #2
    Hyperactive Member progressive's Avatar
    Join Date
    Sep 2001
    Location
    Manchester, UK
    Posts
    404
    ??

    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

  3. #3

    Thread Starter
    Member Vincent Puglia's Avatar
    Join Date
    Feb 2002
    Location
    where the World once stood
    Posts
    36
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width