javascript - 部分循环中未定义的变量,输出
问题描述
我是 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);
解决方案
正如其他人所说,您在第一次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);
推荐阅读
- reactjs - 如何在反应选择中通过 id 设置值
- php - 在PHP中获取两次之间的时间范围
- python - 如何为 2 个 excel 数据框创建 SequenceMatcher 循环
- ssl - NiFi 到 Zookeeper SSL 连接
- python - if re match & group 捕获是否在同一行中?
- c# - 覆盖指定属性的 ToString
- scala - Spark 执行器看不到隐式值 (java.lang.NullPointerException)
- reactjs - 如何在reactjs中正确提醒某些变量姓氏和名字
- docker - 无法使用 Docker 容器内的 Kafka 代理运行控制台使用者
- python - on_message 事件中的 Discord.py 冷却映射