首页 > 解决方案 > 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 次提示

任何帮助谢谢。

标签: javascript

解决方案


howManyTimes是一个字符串,而不是一个数组。

您需要将其转换为数字,然后在循环条件下使用它

let howManyTimes = Number(prompt("how many fruit to want to add?"));

您还可以依靠 javascript 的类型强制转换howManyTimes为数字。因此,您可以跳过显式转换howManyTimes为数字。

for (let index = 0; index < howManyTimes; index++) {
    // code
}

推荐阅读