Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 变量作为for循环中的第二个语句是如何工作的?_Javascript_For Loop_Conditional Statements - Fatal编程技术网

Javascript 变量作为for循环中的第二个语句是如何工作的?

Javascript 变量作为for循环中的第二个语句是如何工作的?,javascript,for-loop,conditional-statements,Javascript,For Loop,Conditional Statements,我试图找到这个问题的答案,如果我太愚蠢而找不到,请原谅我。 如果是这样的话,我很抱歉。但我有这个循环,我不知道为什么它会这样做。 这是Marjin Haverbeke的《雄辩的JavaScript》一书中的练习(第89页,如果有人感兴趣的话) 我的问题是变量“node”如何作为第二个语句工作 非常感谢您的解释 谢谢, 本 输出:['one','two','three']我想您是在问节点如何作为for循环中的第二个表达式工作。Javascript只是将该值计算为true或false,就像说!!节点

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

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

非常感谢您的解释

谢谢, 本


输出:['one','two','three']

我想您是在问
节点如何作为
for
循环中的第二个表达式工作。Javascript只是将该值计算为true或false,就像说
!!节点

// 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将对其求值为true或false)和最终表达式

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
}


用于(
设i=0;//初始化变量i
i<10;//确定循环是否应继续下一次迭代的条件
i++;//增加下一次迭代中使用的i变量的最终表达式
) {
//代码块
}

for
循环的第二条语句中,您需要提供循环运行或停止的条件。因此,它应该是一个输出为
true
false
的东西


在这种情况下,
节点
将具有一些值。如果该值不是
0
null
,则该值的计算结果为
true
。因此,当
节点.rest
返回
null
时。该条件将变为
false
。因此,停止循环。

它使用了JavaScript的真实性概念。欲了解更多信息,请参阅你好先生!非常感谢你的回答。我想我能够缩小我不理解的范围。我很难把脑袋放在嵌套的列表上。绑定本身可以充当语句,这是我实际上知道的,我只是被其他东西弄糊涂了。这个讨厌的小程序让我很难过:)再次感谢
0和
null
不是唯一的“falsy”值。。。有一个空字符串,
undefined
NaN
-0
0n
嘿!谢谢你的回答。如上所述,我的问题(现在你们已经指出了)更多的是围绕嵌套列表的结构进行思考。我现在的任务是了解
node.rest
何时返回
null
,但这正是我的大脑需要重新布线的地方:)@SMEETT。。。在每次迭代之后,您可以在对象中看到,当节点为
{value:'three',rest:null}
时,节点变为null。。。由于该节点的
rest
属性为
null
@Jaromanda。。。我现在觉得自己很蠢,哈哈。但是是的,这很有道理。看到这样使用for循环非常有趣,这让人大开眼界。非常感谢,这让我很开心@斯密特-这是一个非常常见的for循环模式
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
}