【问题标题】:Why does my 'typewriter' iterator print a string in the wrong order?为什么我的“打字机”迭代器以错误的顺序打印字符串?
【发布时间】:2017-04-30 05:10:48
【问题描述】:

抱歉,如果这是一个愚蠢的问题,但我不明白为什么以下代码以看似随机的顺序记录字符串中的字母:

const aString = "hello, this is a string";
const iterator = aString[Symbol.iterator]();

var typewriter =
  setInterval(() => {
    if (iterator.next().done) {
      clearInterval(typewriter);
    } else {
      console.log(iterator.next().value);
    }
  }, 200);

【问题讨论】:

    标签: javascript iterator


    【解决方案1】:

    我不明白为什么以下代码以看似随机的顺序记录字符串中的字母:

    它没有,它跳过所有其他字符。那是因为您在每次迭代中都调用了两次.nextif (iterator.next().done) 将消耗一个字符。只调用一次.next()

    const aString = "hello, this is a string";
    const iterator = aString[Symbol.iterator]();
    
    var typewriter =
      setInterval(() => {
        const next = iterator.next();
        if (next.done) {
          clearInterval(typewriter);
        } else {
          console.log(next.value);
        }
      }, 200);

    【讨论】:

    • 啊!非常感谢。这就说得通了。不过,我太业余了,不知道为什么会发生这种情况。如果您有时间,我将非常感谢您帮助理解这一点?
    • 具体有什么不明白的?
    • 一开始我不明白为什么if (iterator.next().done)会构成一个next()调用。现在我想到它似乎完全荒谬,但在我的脑海中,它会“计数”是没有意义的,因为我的意图只是将它用作 if...else 语句的条件。我对编程很陌生,我不习惯事物中没有隐含的含义:P
    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多