Reputation: 180
I have a genuine quetion. Given this simple JS code:
for (let x of array) {
if (x != array[0]) {
// do stuff
}
}
Is there a way to embed the "if" statement directly into the for loop?
I tried something like this:
for (let x of array if x != array[0] {
// do stuff
}
And:
for (let x != array[0] of array) {
// do stuff
}
But both of them didn't work. Let me know if you can find a solution!
Upvotes: 3
Views: 895
Reputation: 205
If you specifically only want to do stuff on the 2nd - nth element, you can just use a for loop and start at 1 instead of 0.
for (let i = 1; i < arr.length; i++) {
// do stuff
}
Upvotes: 1
Reputation: 121
You cant pass a boolean in a "for of" or "for in" loops , the only way of do a comparison for an iteration of a loop is doing :
let array = ["37","728"];
for (let x = 0 ; ((x < array.length) && array[x] == "37") ; x++){
console.log(array[x]);
}
And it will break the for loop if the second condition pass to true
Upvotes: 1
Reputation: 31992
You can filter the array with the condition and iterate through that result:
const array = [1, 2, 3]
for(let x of array.filter(e => e != array[0])){
console.log(x)
}
Upvotes: 5