#1
  1. No Profile Picture
    Banned
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Apr 2005
    Posts
    4,934
    Rep Power
    0

    Loop through array, do this or that...


    I have an array that contains in this case numbers (integers if it matters).

    I'd like to cycle through the array and see if any match a certain number.

    There is only the possibility of ONE match, the number will only match one array element.

    If there is a match, do X, if not, do Y.

    I know how I would do this simple task in PHP, but I'm still a JS n00b.

    Any help would be very much appriciated.
  2. #2
  3. No Profile Picture
    I AM A GOLDEN GOD
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Apr 2003
    Location
    Camarillo, California
    Posts
    5,929
    Rep Power
    1170
    If the order of the loop doesn't matter, a decrementing while() loop is most efficient:
    Code:
    // you array
    var list=[1,3,5,7,9,11];
    // number you're searching for
    var n= 3;
    // the list length (sizeof(list))
    var len= list.length;
    // while loop
    while( len-- ) {
      // if the value is found
      if ( list[len] === n ) {
        // action X
        alert( "Found it!\n" +n );
        // optionally stop the loop here with a break statement
      } else {
        // action Y
      }
    }

    Comments on this post

    • Arty Ziff agrees : Ahhhhh.... Thanks!
    "Seriously, we're not a search engine, we're actual people." ~ ManiacDan

    BookMooch.com : Give books away. Get books you want.
  4. #3
  5. Cunning Linguist
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2003
    Location
    I used to live at home, now I stay at the house
    Posts
    10,166
    Rep Power
    2043
    Yeah, JS doesn't have anything native like PHP's in_array() method,
    but that's not to say you can't replicate the functionality.

    You could make a global function and call it like you do in PHP:
    http://samsami2u.wordpress.com/2009/...s-seen-in-php/

    Or you could be stricter and prototype the Array object:
    http://snippets.dzone.com/posts/show/4653

    Comments on this post

    • lnxgeek agrees : IMHO the second function linked is MUCH better.
    Support requests via PM will be ignored!
    Read These: The General Rules Thread | The General FAQ Thread | NEW USERS - How to post a question

  6. #4
  7. No Profile Picture
    Banned
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Apr 2005
    Posts
    4,934
    Rep Power
    0
    This "prototype" thing looks like the way to go...

    Since I'm new at this JS stuff, I'm trying to use only "best coding practices" and such. I'm going for speed and bullet proof and by-the-book. I want small without iffy shortcuts.

IMN logo majestic logo threadwatch logo seochat tools logo