【问题标题】:Is there any easier way to code this in JavaScript (while loop and switch statement)?有没有更简单的方法可以在 JavaScript 中进行编码(while 循环和 switch 语句)?
【发布时间】:2017-10-15 13:25:54
【问题描述】:

我想知道是否有另一种更简单的方法可以在 JavaScript 中获得此类代码的相同结果。我每次都使用 while 循环 来减少数字,但后来我不得不使用 switch 语句 来更改单词字符串中的“bottles”从复数到单数,因为瓶子的数量从 1 下降到 0。

var num = 99;
//The following code repeats the sentence with changing number gradually.
while (num>2) {
console.log(num + " bottles of juice on the wall! " + num + 
" bottles of juice! Take one down, pass it around..." + (num-1) 
+ " bottles of juice on the wall!" );
num = num - 1;

}

//then this code is for bottle to be singular as the number decrease to be 1 
then zero
switch (num){

case 2 :
console.log(num + " bottles of juice on the wall! " + num + 
" bottles of juice! Take one down, pass it around..." + (num-1) 
+ " bottle of juice on the wall!" );


case 1 :
console.log((num-1) + " bottles of juice on the wall! " + (num-1) + 
" bottles of juice! Take one down, pass it around..." + (num-2) 
+ " bottle of juice on the wall!" );

}

【问题讨论】:

    标签: javascript while-loop switch-statement


    【解决方案1】:

    通常你会创建一个函数以复数或单数形式返回单词。

    function bottles(num) {
      if( num === 1 ) {
        return '1 bottle';
      }
      
      return num + ' bottles';
    }
    
    for( var num = 99; num > 0; num-- ) {
      console.log(bottles(num) + " of juice on the wall! " + bottles(num) +
        " of juice! Take one down, pass it around... " + bottles(num - 1) +
        " of juice on the wall!");
    }

    【讨论】:

    • 谢谢。我只是一个初学者,开始使用 while 循环学习循环,然后这是一个关于 while 循环的测验。我认为您使用了我听说过但尚未学习的 for 循环和函数。
    猜你喜欢
    • 2018-09-16
    • 2013-12-20
    • 1970-01-01
    • 2021-03-08
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多