首页 > 解决方案 > 部分循环中未定义的变量,输出

问题描述

我是 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);

标签: javascriptloops

解决方案


正如其他人所说,您在第一次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);

推荐阅读