Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

A question about the execution sequence in Javascript Iterator

class iteratorWithoutG {
  [Symbol.iterator]() {
    let val = 0;
    let threshold = 10;
    return {
      next() {
        if(val >= threshold) {
          console.log('iteratorWithoutG is finished');
          return {
            done: true,
            value: undefined
          } 
        }
        return {
          done: false,
          value: val++
        }
      },
      return() {
        return {
          done: true,
          value: undefined
        } 
      }
    }
  }
}
const iWithoutG = new iteratorWithoutG(10);
console.log([...iWithoutG]);

I was learning things about the JS iterator, and I got this:

iteratorWithoutG is finished
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

I wondered why the String was displayed before the Array, so I added some logs:

class iteratorWithoutG {
  [Symbol.iterator]() {
    let val = 0;
    let threshold = 10;
    return {
      next() {
        if(val >= threshold) {
          console.log('iteratorWithoutG is finished');
          console.log(Date.now())
          return {
            done: true,
            value: undefined
          } 
        }
        return {
          done: false,
          value: (val++, Date.now())
        }
      },
      return() {
        return {
          done: true,
          value: undefined
        } 
      }
    }
  }
}

This time I get this message:

iteratorWithoutG is finished
1610466807875
[ 1610466807872,
  1610466807872,
  1610466807872,
  1610466807872,
  1610466807872,
  1610466807872,
  1610466807872,
  1610466807872,
  1610466807872,
  1610466807872 ]

So the string was in fact generated after the Array, but how can it be displayed before the Array?? Was the Array stored somewhere?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This line:

console.log([...iWithoutG]);

De-sugars to:

{
  let arr = [];
  for (const e of iWithoutG) {
    arr.push(e);
  }
  console.log(arr);
}

That means that first, the array is created and populated, and only then console.log() is called. So the iterator finishes before the call to console.log().

Full order of events:

  1. The array and the iterator are initialized.
  2. The iterator's next() method is called until it's done and the results are pushed into the array.
  3. The iterator finishes.
  4. The array is logged to the console.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...