javascript - javascript:如何在 for 循环中使用 javascript 数组
问题描述
我是 js 的新手,所以我的代码不起作用
我的代码是:
let output = document.getElementById("output");
let addfruit;
let fruitList = [];
let howManyTimes = prompt("how many fruit to want to add?");
for (let index = 0; index < howManyTimes.length; index++) {
addfruit = prompt("enter fruits name");
if (addfruit == "no") {
break;
}
fruitList.push(addfruit);
}
for (myShop of fruitList) {
output.innerHTML += myShop + "<br/>";
}
我的问题是,当我想要 5 次提示时,我只会得到 1 次提示
任何帮助谢谢。
解决方案
howManyTimes
是一个字符串,而不是一个数组。
您需要将其转换为数字,然后在循环条件下使用它
let howManyTimes = Number(prompt("how many fruit to want to add?"));
您还可以依靠 javascript 的类型强制转换howManyTimes
为数字。因此,您可以跳过显式转换howManyTimes
为数字。
for (let index = 0; index < howManyTimes; index++) {
// code
}
推荐阅读
- reactjs - 我应该使用 react-native-web 将 React-native 应用程序转换为 Web 应用程序还是在 React JS 上从头开始实现它
- python - 在 Windows 版本 6.3.9600 和 python 3.8.0 上为 pycharm 安装 Jupyter notrebook
- javascript - 更改反应钩子中的处理程序
- ios - 删除项目 RxSwift MVVM 模式
- angular - 使用 cdk Angular 材料将卡片从容器移动到相应的容器
- typescript - 如何覆盖外部 TypeScript 接口
- redis - Redis 内存使用和信息内存
- python - 当 x 范围为 0、0.001、0.01、...、1000 时,如何手动拆分 matplotlib 散点图的 x 轴?
- haskell - 如果恢复容器很困难,“Store”comonad 的意义何在?
- c# - Drop 事件在继承的面板上触发两次