有没有更简单的方法在JavaScript中编写代码(while循环和switch语句)?

时间:2017-10-15 13:25:55

标签: javascript while-loop switch-statement

我想知道是否还有另一种更简单的方法可以在JavaScript中获得相同的代码结果。我使用 while循环 来减少每次的数量,但之后我不得不使用 switch语句 来更改单词"的"在从多个到单数的字符串中,随着瓶数下降到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!" );

}

1 个答案:

答案 0 :(得分:0)

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

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!");
}