Reputation: 139
I have a simple array that I want to run in a loop. While I want to log each value of the array to the console, I also want to log a string only IF the index of the array matches the value of a variable..
Here is what I got.
let myVal = 10;
let digit = [12,4,11,10]
for (let i = 0; i < digit.length; i++) {
console.log(digit[i]);
if (myVal == digit[3]) {
console.log(digit[3] && ' Hooray!');
}
}
What I am seeing is the console is logging both, so I get this:
12
Check!
4
Check!
11
Check!
10
Check!
I am looking for something like this:
12
4
11
10 Check!
Upvotes: 0
Views: 117
Reputation: 188
You need to evaluate against the current index.
I would suggest something like this
let myVal = 10;
let digit = [12, 4, 11, 10]
for (let i = 0; i < digit.length; i++){
if (digit[i] == myVal)
console.log(digit[i] + 'Hooray!');
} else {
console.log(digit[i]);
}
}
Or just use a for in loop which looks like this:
for (x in digit) {
if (digit[x] == myVal)
console.log(digit[x] + 'Hooray!');
} else {
console.log(digit[x]);
}
}
Also && is used for "and" in evaluations and + is used for concatenation of string.
Upvotes: 0
Reputation: 5648
Small error on your loop.
Always use your iterator when you have an if inside a loop
Hope it helps
let myVal = 10;
let digit = [12, 4, 11, 10]
for (let i = 0; i < digit.length; i++) {
if (digit[i] == myVal)
console.log(digit[3] + ' Check!');
else
console.log(digit[i]);
}
Upvotes: 0
Reputation: 35
You want check the indexes ?
for (let i = 0; i < digit.length; i++) {
console.log(digit[i]);
if (myVal == digit[i]) //check the index not digit[3] every loop
console.log(digit[i] + ' Hooray!'); //print the index using string concatenation
}
im also noob :)
Upvotes: 3
Reputation: 71
Since you're in a loop, you won't need to check for digit[3], you can just check for digit[i].
let myVal = 10;
let digit = [12, 4, 11, 10];
for (let i = 0; i < digit.length; i++) {
if (digit[i] == myVal){
console.log(digit[i] + ' Hooray!');
} else {
console.log(digit[i]);
}
}
I also added an else for printing the rest of the digits separately. Lastly, you'll want to use "+" instead of "&&" if you want to append text to your result.
Upvotes: 3