0

I have to search in array items using for loop without any "method", "function" or "break" syntax. I wrote this code bud does not work!

var array = [12, "Data", true, "S"]

var searchItem = "Data"

var i

for (i = 0; i < array.length; i++) {
    if (array[i] == searchItem) {
        console.log("Item Found")
    } else {
        console.log("Item Not Found")
    }
}

5
  • Please try to explain "does not work!" with more specifics. Commented Oct 31, 2018 at 23:08
  • It works for me, what seems to be the problem? Commented Oct 31, 2018 at 23:08
  • This will be print: Item Not Found Item Found Item Not Found Item Not Found Commented Oct 31, 2018 at 23:09
  • 1
    @MasoodSadri Even when you click "Run code snippet", it works:) It does so because you want to log something to the console on every iteration. Commented Oct 31, 2018 at 23:09
  • It does't work! I mean this loops doesn't show jus ONE result! Commented Oct 31, 2018 at 23:14

1 Answer 1

1

It's a little difficult to decipher what you're after, but are you looking for something like this?

var array = [12, "Data", true, "S"];
var searchItem = "Data";
var i;
var found = false;

for (i = 0; i < array.length; i++) {
  if (array[i] == searchItem) found = true;
}

console.log(found?'Item Found':'Item Not Found');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.