Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

JavaScript arrays and loops combination question

  1. Sep 18, 2012 #1
    var lost = [4, 8, 15, 16, 23, 42];
    var count = lost.length;

    var isLost = function (n) {
    for (i=lost[0]; i<count; i=lost[i+1]) {
    if ( n === lost) {
    return "true";
    }
    }
    return "false";
    };

    is it possible to in corporate array positions into the for loop? (i)
    do I even begin to approach the correct "incorporation"? (ii)
     
  2. jcsd
  3. Sep 18, 2012 #2

    Filip Larsen

    User Avatar
    Gold Member

    As I understand your questions:
    (i) Use i = i+1, or i++ as the increment.
    (ii) You would want to return the boolean literals true or false instead of their string representation. You may also want to check out the array indexOf operation [1].

    [1] http://www.w3schools.com/jsref/jsref_indexof_array.asp
     
  4. Sep 18, 2012 #3

    Borg

    User Avatar
    Gold Member

    You should do something like this to read the contents of an array. Don't forget to declare var i and n (whatever that is):
    Code (Text):

    for(var i = 0; i < lost.length; i++){
        if(n == lost[i]){
            return true;
        }
    }
     
    var i in the for loop is the position of the array that you are examining.
     
  5. Sep 19, 2012 #4
    Thanks.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: JavaScript arrays and loops combination question
Loading...