jeffr
jeffr

Reputation: 35

Looping in Javascript array

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>

Upvotes: 1

Views: 98

Answers (3)

AlexStack
AlexStack

Reputation: 17381

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.

Upvotes: 1

Piotr Dajlido
Piotr Dajlido

Reputation: 2030

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!

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074058

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;

Upvotes: 1

Related Questions