【问题标题】:Need help understanding why my code works the way it does (JS)需要帮助理解为什么我的代码会以它的方式工作(JS)
【发布时间】:2021-04-22 23:46:00
【问题描述】:

我创建了这段代码,作为我学习 JS 课程的一部分,我是初学者,所以我不太明白这里发生了什么。有问题的代码部分在最后指出“1 瓶”而不是“1 瓶”和“0 瓶”而不是“0 瓶”,这是正确的,但我不确定如何。如果我将 'console.log (numberOfBottles + " " + bottleWord + " of beer on the wall.");' 的底部代码 sn-p 放在 'If' 语句上方,则 '1 bottle' 变为'1瓶'和'0瓶'变成'0瓶',这是错误的。但是,我不明白是什么导致它改变以及为什么。我希望我已经解释得足够清楚了,任何帮助将不胜感激。

function beerSong() {
var numberOfBottles = 99;
var bottleWord="bottles";

while (numberOfBottles>0) {

   console.log (numberOfBottles + " " + bottleWord + " of beer on the wall, " + numberOfBottles + " " + bottleWord + " of beer. Take 1 down, pass it around,");

   numberOfBottles--;


   if (numberOfBottles===1){
  bottleWord="bottle";
   }
   if (numberOfBottles===0){
     bottleWord="bottles";
   }

   console.log (numberOfBottles + " " + bottleWord + " of beer on the wall.");
   
}
}

beerSong();

【问题讨论】:

    标签: javascript


    【解决方案1】:

    通过预测 numberOfBottles--; 行之前的 if 语句,您可以在减少变量之前检查变量的数量。

    以您的代码为例并考虑循环周期,其中numberOfBottles 开头等于 2:

    ...
        // Here numberOfBottles is 2
        numberOfBottles--;
    
        // Here numberOfBottles is 1
        if (numberOfBottles===1) {
            // bottleWord gets updated to "bottle"
            bottleWord="bottle";
        }
        if (numberOfBottles===0) {
            bottleWord="bottles";
        }
    
        // This will print: "1 bottle of beer on the wall."
        console.log (numberOfBottles + " " + bottleWord + " of beer on the wall.");
    ...
    
    ...
        // Here numberOfBottles is 2, bottleWord doesn't get update since it's not 1 or 0
        if (numberOfBottles===1) {
            bottleWord="bottle";
        }
        if (numberOfBottles===0) {
            bottleWord="bottles";
        }
    
        numberOfBottles--;
    
        // Here numberOfBottles is 1
    
        // This will print: "1 bottles of beer on the wall."
        console.log (numberOfBottles + " " + bottleWord + " of beer on the wall.");
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2018-10-06
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多