Yawei Song
Yawei Song

Reputation: 1

How to make instance in for...of in ES6?

for (let i = 0; i < stars.length; i++) {
        stars[i] = new Star()
}

works!

for (let star of stars) {
        star = new Star()
}

Not work! I want to make 100 instances of Star once. i can make them in traditional JS. But if i use for...of in ES6, it doesn't work. Why?

Upvotes: 0

Views: 83

Answers (2)

sonEtLumiere
sonEtLumiere

Reputation: 4562

I hope this 3 examples helps, its working.

for in: each index (stars = 0, 1, 2, 3, 4, 5)
for of: each value (stars = "c", "i", "n", "c", "o")

class Star {
  constructor(number){
    this.num = number
  }
}

var stars = "cinco";
console.log(stars.length);


for (let i = 0; i < stars.length; i++) {
  console.log(stars[i] = new Star(i));
}


for (let star of stars) {
  console.log(star = new Star(star));
}


for (let star in stars) {
  console.log(star = new Star(star));
}

Upvotes: 0

Manasi Agte
Manasi Agte

Reputation: 11

When accessing the traditional loop you are not dependent on the entity like array, set, of just series of intergers, they iterate on the condition maintained in their syntax, hence whatever we are doing inside the loop has no connection with the loop, it will iterate till it's condition,

where as for of loop is specifically meant for array/ set or an iterable object and for (variable of object) statement

variable here is actual value in that object, not the reference of that value ( like traditional for loop you are accessing i th index position in the array, not actual value of array .

Upvotes: 1

Related Questions