【问题标题】:How does a variable as a second statement in a for-loop work?变量作为 for 循环中的第二条语句如何工作?
【发布时间】:2020-09-09 22:03:39
【问题描述】:

我试图找到这个问题的答案,如果我太愚蠢而无法找到它,请原谅我。 如果是这样的话,我很抱歉。但是我有这个循环,我不知道它为什么会这样做。 这是 Marjin Haverbeke 的“Eloquent JavaScript”一书中的一个练习(第 89 页,如果有人感兴趣的话)

我的问题是变量“node”如何作为第二条语句工作。

任何解释都非常感谢!

谢谢, 本

list = { value: 'one', rest: { value: 'two', rest: { value: 'three', rest: null }}};

function listToArray(list) {
    let array = [];
    for (let node = list; node ; node = node.rest) {
      array.push(node.value);
    }
    return array;
  }

console.log(listToArray(list));

输出:['一','二','三']

【问题讨论】:

  • 它使用了 JavaScript 的 Truthiness 概念。有关详细信息,请参阅Truthy page on MDN

标签: javascript for-loop conditional-statements


【解决方案1】:

我相信您在问node 如何作为for 循环中的第二个表达式工作。 Javascript 只是将该值评估为真或假,就像说!!node

// to simplify the for loop, the variable node starts with the list
// and if the node exists executes the code block inside and continues the loop
// when node.rest becomes null the loop exits 
for (let node = list; node ; node = node.rest) {
      array.push(node.value);
}

为了进一步解释 for 循环是如何工作的,它由三个表达式组成,初始化器、条件(js 将评估为真或假)和最终表达式。

for (
  let i = 0; // initializes the variable i
  i < 10;    // condition that determines whether the loop should continue next iteration or not
  i++;       // final-expression which increments the i variable to be used in the next iteration

) {
 // code block
}


【讨论】:

  • 先生您好!非常感谢您的回答。我想我可以缩小我不明白的范围。我很难把头绕在嵌套列表上。绑定可以充当语​​句本身是我实际上知道的,我只是被别的东西弄糊涂了。这个讨厌的小程序让我很难过 :) 再次感谢!
【解决方案2】:

for 循环的第二条语句中,您需要提供循环运行或停止的条件。因此,它应该提供truefalse 的输出。

在这种情况下,node 将具有一定的价值。如果该值不是0null,则该值被评估为true。所以,当node.rest 返回null。条件将变为false。因此,停止循环。

【讨论】:

  • 0null 不是唯一的“假”值......还有一个空字符串,undefinedNaN-00n
  • 嘿!谢谢您的回答。如上所述,我的问题是(现在你们已经指出了)更多的是关于将我的头包裹在嵌套列表的结构上。我现在的任务是了解node.rest 何时返回null,但这是我的大脑需要重新布线的东西:)
  • @SMEETT ...您在每次迭代后分配node = node.rest,您可以在对象中看到当节点为{ value: 'three', rest: null }时节点变为空...因为该节点的rest属性是null
  • @Jaromanda ...我现在觉得自己很愚蠢,哈哈。但是,是的,这很有意义。看到这样使用 for 循环非常有趣,这令人大开眼界。非常感谢,这让我很开心!
  • @SMEETT - 这是 for 循环的非常常见模式
猜你喜欢
  • 1970-01-01
  • 2021-07-12
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 2023-03-07
  • 2015-09-14
  • 2018-02-25
相关资源
最近更新 更多