【发布时间】: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