Reputation: 2048
It is possible to define multiple variables in a for-of
loop like in the code below?
let arr = ['red', 'green', 'blue'];
for (let x = 0, y of arr){
console.log(x++, y);
}
EDIT:
let arr = ['red', 'green', 'blue'];
let x = 0;
for (let y of arr){
console.log(x++, y)
}
So i want to convert this code into the first one (or like that) and thus reduce number of code lines.
Upvotes: 1
Views: 1392
Reputation: 664640
No, you cannot declare-and-initialise variables normally (like you can in for
loops) in for … of
or for … in
loops.
What you can do though is destructuring, and for your use case there's the .entries()
iterator that includes an index:
for (let [x, y] of ['red', 'green', 'blue'].entries())
console.log(x, y);
Upvotes: 5
Reputation: 1423
No, it isn't possible, you can define only one variable in for...loop. Compilers such as babel or es6fiddle returns an error for such definition.
Upvotes: 1