2

I have a simple quesetion and I'm not sure why the array content is not being returned properly. I'm pretty sure this is something simple but somehow I'm not getting the results I want. The scenario is that a variable "compare" is set to a value e.g. "apple" and I am looping into the array, and, if apple matches an index print that into the text field. It doesn't do it and it always says the "not the same" value. For value dog it works. It seems like it reaches the last array then does comparisons. Help please.

Code below

<!DOCTYPE html>
<html>
<body>

<script>
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";

for (i = 0; i < arr.length; i++) {

    if (arr[i] == compare) {text = "The value is " + arr[i] + "<br>";  }

    else if (compare == "" || compare == null) { text = "The value is blank"; }

    else if (arr[i] != compare) {text = "not the same"; }

else {text ="some error";}

    }

     document.getElementById("demo").innerHTML = text;
}
</script>
<p>Click the button to do a loop with a break.</p>

 <button onclick="myFunction()">Try it</button>


<p id="demo"></p>

</body>
</html>
2
  • It would work if the apple was the last item in the array. Does that help?
    – Bergi
    Commented Mar 16, 2015 at 16:13
  • Side note: Your final else will never be used, because your previous conditions cover all possibilities. In particular, you have a if (arr[i] == compare) and a if (arr[i] != compare). Unless you were comparing with NaN (which has the unusual behavior of never being either == or != to anything), one of those two will be true. Commented Mar 16, 2015 at 16:14

3 Answers 3

1

function print(msg) {
  document.getElementById("demo").innerHTML += msg + '</br>';
}

function myFunction() {
  var text = "";
  var i;
  var arr = ["apple", "banana", "carrot", "dog"];
  var compare = document.getElementById('compare').value;
  if (!compare) {
    print('Compare is empty');
    return;
  } else {
    print('Comparing with ' + compare);
  }

  for (i = 0; i < arr.length; i++) {
    if (arr[i] == compare) {
      print("The value is at index " + i + " is " + arr[i]);
      return; //results found, break out of the for loop
    } else if (arr[i] != compare) {
      print("not the same");
    } else {
      print("some error");
    }
  }
  print("Could not find " + compare + " in array");
}
<!DOCTYPE html>
<html>

<body>

  <script>
  </script>
  <p>Click the button to do a loop with a break.</p>

  <input type="text" id="compare" placeholder="Compare to" />
  <button onclick="myFunction()">Try it</button>


  <p id="demo"></p>

</body>

</html>

For performance reasons it is better to validate the value of compare before the loop starts. You can break out of the loop using break, continue or return keywords.

4
  • You are a life saver! I always printed the html element and for some reason the loop goes crazy that way. The print function was a good helper function that I would have never used!
    – jeffr
    Commented Mar 16, 2015 at 16:41
  • You are welcome. Also the whole array searching algorithm that you wrote already exists in javascript. See this: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
    – AlexStack
    Commented Mar 16, 2015 at 17:14
  • the purpose of my inquiry is to solidify syntax and be familiar with it. Altogether I am going to call a JSON file and loop through it. I read the mozilla docs and it helps but for my implementation I wanted it to be simple. I really appreciate your help! :) I learned a new thing today! :D
    – jeffr
    Commented Mar 16, 2015 at 19:31
  • If you want to browse through JSON files or in general big Javascript array and objects, take a look at underscore. It is a big time saver: underscorejs.org
    – AlexStack
    Commented Mar 17, 2015 at 6:55
1

It seems like it reaches the last array then does comparisons. Help please.

In effect, yes, because you never stop the loop. So all of the previous assignments you've done to document.getElementById("demo").innerHTML are overwritten by the final one.

If you want to stop when you find a match, use break to break out of the loop.

If you want the element to have a list of what had happened (which I think might be what you were trying to do, it's hard to tell), build the list up in text and then assign at the end:

if (compare == "" || compare == null) {
    // Doesn't make sense to loop in this case, presumably
    text = "The value is blank";
} else {
    text = "";
    for (i = 0; i < arr.length; i++) {

        if (arr[i] == compare) {
            text += "The value matches " + arr[i] + "<br>";
            //   ^--- note the +=
        } else {
            text += "The value doesn't match " + arr[i] + "<br>";
            //   ^--- note the +=
        }
    }
}
document.getElementById("demo").innerHTML = text;
0

You never break the for loop. You must use break; to exit the loop when the if condition is met.

Here your is your solution: http://jsfiddle.net/urahara/rvLyfsto/

and your code:

function myFunction() {
    var text = "";
    var i;
    var arr = ["apple", "banana", "carrot", "dog"];
    var compare = "apple";

    for (i = 0; i < arr.length; i++) {

        if (arr[i] == compare) {
            text = "The value is " + arr[i] + "<br>";
            break;
        } else if (compare == "" || compare == null) {
            text = "The value is blank";
            break;
        } else if (arr[i] != compare) {
            text = "not the same";
            break;
        } else {
            text = "some error";
            break;
        }

    }

    document.getElementById("demo").innerHTML = text;
}

Cheers!

Not the answer you're looking for? Browse other questions tagged or ask your own question.