Reputation: 153
I'm having trouble with a for loop. I want to return the index that matches with num
against fruits. When num=2
, I want it to return "apple". What am I doing wrong?
var num=2;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (var i=0;i <fruits.length;i++) {
if (fruits[i] === num) {
console.log("matched, it is" + fruits[num])
} else {
console.log("did not match")
}
}
Upvotes: 2
Views: 95
Reputation: 53038
The condition that you should be checking against is
if(i === num)
instead of if(fruits[i] === num)
.
You want to compare index i
against number num
and not the value at index i
in fruits
array against num
.
For example: fruits[0]
is "Banana", fruits[1]
is "Orange",...so on. What you are doing is comparing "Banana", "Orange",...etc against num
value 2 when you should be comparing value of i
which goes from 0,1,..3 against num
value 2.
Also, like @Kamyar pointed out, you can directly access fruits[num]
, probably after a sanity check in case fruits
gets populated from an outside source:
var num=2;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
if(fruits != null && num >= 0 && num < fruits.length) {
console.log("matched, it is " + fruits[num])
}
else{
console.log("did not match")
}
Upvotes: 2
Reputation: 11579
You have to compare num
with array index i
:
if (i == num) {
console.log("matched, it is" + fruits[num])
}
Upvotes: 1
Reputation: 41893
if (fruits[i] === num) {...}
- fruits[i]
is an element inside the fruits
array at i
position, not an index. Compare it with the index i === num
instead.
var num = 2,
fruits = ["Banana", "Orange", "Apple", "Mango"];
for (var i = 0; i < fruits.length; i++) {
if (i === num) {
console.log("matched, it is " + fruits[num])
} else {
console.log("did not match")
}
}
Upvotes: 1