在循环的一部分中未定义的变量,输出

时间:2018-06-22 13:10:55

标签: javascript loops

我是JS的初学者,我想知道为什么第一个循环结果输出一个“未定义”变量,而其余的都包含“瓶”。它的意思是输出从99到1的语句。

以下是代码段:

/*
 * Programming Quiz: 99 Bottles of Juice (4-2)
 *
 * Use the following `while` loop to write out the song "99 bottles of juice".
 * Log your lyrics to the console.
 *
 * Note
 *   - Each line of the lyrics needs to be logged to the same line.
 *   - The pluralization of the word "bottle" changes from "2 bottles" to "1 bottle" to "0 bottles".
 */

var num = 99;
let statementSplit = ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
while (num > 0) {
  var bottles = (num > 1 ? "bottles" : "bottle");
  statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
  // var statementSplit=((num+" "+bottles+" of juice on the wall! " + num + " "+ bottles+" of juice! Take one down, pass it around... "));
  num = num - 1;
}
console.log(statementSplit);

4 个答案:

答案 0 :(得分:2)

将“ let”替换为“ var”,并使用var java脚本允许“提升” ...

答案 1 :(得分:0)

在您第一次调用bottles时,let statementSplit...并没有用双引号引起来。相反,应该是

let statementSplit = ((num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... "));

答案 2 :(得分:0)

尝试使用编辑后的代码段。在开始声明时,应将瓶子作为字符串而不是变量添加。

/*
 * Programming Quiz: 99 Bottles of Juice (4-2)
 *
 * Use the following `while` loop to write out the song "99 bottles of juice".
 * Log your lyrics to the console.
 *
 * Note
 *   - Each line of the lyrics needs to be logged to the same line.
 *   - The pluralization of the word "bottle" changes from "2 bottles" to "1 bottle" to "0 bottles".
 */

var num = 99;
let statementSplit = ((num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... "));
while (num > 0) {
  var bottles = (num > 1 ? "bottles" : "bottle");
  statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
  // var statementSplit=((num+" "+bottles+" of juice on the wall! " + num + " "+ bottles+" of juice! Take one down, pass it around... "));
  num = num - 1;
}
console.log(statementSplit);

答案 3 :(得分:0)

正如其他人所述,您确实在第一个statementSplit分配中有一个未定义的变量。 我也会在while循环内移动第一个statementSplit分配,以增加可维护性(以防将来需要更改歌词):

var num = 99;
let statementSplit = "";
while (num > 0) {
    var bottles = (num > 1 ? "bottles" : "bottle");
    statementSplit += ((num + " " + bottles + " of juice on the wall! " + num + " " + bottles + " of juice! Take one down, pass it around... "));
    num = num - 1;
}
console.log(statementSplit);