Javascript似乎在实现时跳过一行(如果count === 1)

时间:2016-05-07 17:49:29

标签: javascript

我正在教科书中练习,但没有为其作业提供答案或示例。这是历史悠久的99瓶啤酒墙上的javascript程序。在网上搜索之后,我发现的例子的编码方式与本书到目前为止的教学方式截然不同。我的问题是,当我到达底部(1瓶)时,第一行总是说“1瓶”,即使其余部分调整为“1瓶”。我不确定我做错了什么,但我渴望学习!感谢大家!我已经加入了一个jsfiddle。

var word = "bottles";
var count = 99;
while (count > 0) {
    console.log(count + " " + word + " of beer on the wall ");
    console.log(count + " " + word + " of beer,");
    console.log("Take one down, pass it around,");
    count = count - 1;
    if (count > 0) {
        console.log(count + " " + word + " of beer on the wall."); 
    if (count === 1)
        word = "bottle";
    } else {
            console.log("No more bottles of beer on the wall.");
    }
}

https://jsfiddle.net/mmaffia92/3jp0fjya/

2 个答案:

答案 0 :(得分:0)

你只需要移动几条线,特别是移动线不再是循环外的 ,否则它将永远不会运行(计数总是大于0 in循环)。

var count = 99;
var word;

while (count > 0) {
  var word = count === 1 ? "bottle" : 'bottles';
  console.log(count + " " + word + " of beer on the wall");
  console.log(count + " " + word + " of beer,");
  console.log("Take one down, pass it around,");
  count = count - 1;
  if (count > 0) {
    word = count === 1 ? "bottle" : 'bottles';
    console.log(count + " " + word + " of beer on the wall.");
    console.log('');
  }
}


console.log("No more bottles of beer on the wall.");

DEMO

如果您愿意,可以使用三元表达式替换if语句,以使其更简洁:

var word = count === 1 ? 'bottle' : 'bottles';

答案 1 :(得分:0)

您的代码记录“墙上有1瓶啤酒”的原因。是因为您在之后更改了word 的值,因此您记录了该表达式。要在对代码进行最少量更改的同时修复此问题,您只需要颠倒console.logif (count > 0) { if (count === 1) { word = "bottle"; } // Note that the log will occur after the word = "bottle" assigment. console.log(count + " " + word + " of beer on the wall."); } else { console.log("No more bottles of beer on the wall."); } 的条件分配顺序:

word = "bottle";

此外,我想要注意的是,我在else块周围添加了花括号。这些都不是必需的,但是,我认为,使代码更具可读性。乍一看,您的if (count === 1)区块看起来与if (count > 0)相对应,但它实际上对应于fopen()