【问题标题】:Basic While loop query - why is "1" logged?基本 While 循环查询 - 为什么记录“1”?
【发布时间】:2015-10-17 18:52:48
【问题描述】:

为什么这个while循环最后打印“1”?..我只希望它打印console.log语句。使用 Codecademy 时看到的。

for (i = 0; i < 2; i++) {
    console.log("I understand for loops twice..lol");
};

var whileUnderstand = 0;

while(whileUnderstand < 2) {
    console.log("I understand while loops twice..lol");
    whileUnderstand++;
}  

那个问题没有我问的问题的直接答案。此外,它只包含 console.log 语句而不是循环。主要是没有答案说“控制台只是输出语句的最后评估值”。这是解决我问题的答案。

【问题讨论】:

  • @KushJain 你的其余代码在哪里?
  • @j08691 将其粘贴到控制台中。
  • 您是从浏览器控制台运行它吗?当我从 IE 控制台尝试此操作时,它似乎在增加之前打印了 ++ 语句的值。例如,当我运行var a = 0; a++; 时,它会打印出0
  • 这只是该代码块的返回值,就像它是一个函数一样运行。在 while 循环之后添加另一行,表示 whileUnderstand++;,您将得到 2 而不是 1。
  • @B.Kemmer “为什么最后会打印‘1’?”。这实际上是 OP 的问题...

标签: javascript loops for-loop while-loop


【解决方案1】:

只有在浏览器控制台中运行代码时才会发生这种情况。

这是由这一行引起的:

whileUnderstand++;

控制台只是输出语句的last评估值。


仅记录1 而未记录0 的原因是在console.log() 调用之外,仅记录最后一条语句。

例如,如果我有以下代码 sn-p 仅记录 "d"

var a = "a";
var b = "b";
a = "c";
b = "d";

【讨论】:

  • 你能解释一下为什么它似乎只打印1,而不是2吗?另外,为什么它似乎打印了1 之后 两次都打印了预期的console.log('...') 语句?
  • 因为你使用whileUnderstand++。它是后缀运算符:它在增加之前返回值。试试前缀++whileUnderstand,你会得到2。
  • 为什么这只发生在浏览器控制台中?
  • @KushJain 好在哪里以及为什么 javascript 会打印这个值?控制台 = 输入 -> 输出(即使它未定义)
  • @jmar777 如果你在while循环中反转console.logwhileUnderstand++的调用,你会得到undefined。我猜控制台输出最新的“评估”值。
【解决方案2】:
var whileUnderstand= 0;

while(whileUnderstand<2) {
    console.log("I understand while loops twice..lol");
    whileUnderstand++;
}  

因为whileUnderstand 等于 2 时它不会增加,如果你想打印 2,你需要这样做

var whileUnderstand= 0;

while(whileUnderstand<3) {
    console.log("I understand while loops twice..lol");
    whileUnderstand++;
}  

【讨论】:

    猜你喜欢
    • 2011-10-11
    • 2019-05-29
    • 2020-06-20
    • 2013-03-11
    • 2016-09-01
    • 1970-01-01
    • 2020-10-30
    • 2018-03-27
    • 2021-04-02
    相关资源
    最近更新 更多