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


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    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
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Threads - JavaScript arrays loops Date
JavaScript Editable html table and javascript Mar 27, 2017
Javascript Compatibilty issue Dec 26, 2016
JavaScript How to communicate between javascript and php? Oct 10, 2016
Regarding open pdf Sep 23, 2016
Problem working with multi-dimensional arrays in Javascript Sep 9, 2016