数组中的元素无法识别

Elements in the array not recognized

    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }
    <div id="list"></div>

for 循环似乎无法正常工作,因为它正在将用户输入添加到列表中,但它无法识别数组中的元素。我没有在此处添加的列表具有 id="list" 并且它具有数组中的三个元素。谢谢!

  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }

我编辑了你的代码更有意义。

是不是和你期待的差不多?

var userInput = prompt('Which fruit would you like?');
var fruitList = ["banana", 'strawberries', "mango"];
let newItem = false;
for (let i = 0; i < fruitList.length; i++) {
  if (userInput == fruitList[i]) {
    newItem = false;
    alert("Sorry, we are out of " + userInput);
  } else {
    newItem = true;
  }
}
if (newItem) {

  let userFruit = document.createElement('li');
  userFruit.innerHTML = userInput
  let fruits = document.getElementById('list');
  fruits.appendChild(userFruit);
}
<ul id="list">

</ul>

您应该将花括号添加到 for 循环中...这不是必需的,但它本质上更整洁。您的问题是语法,因为您在终止循环的 for 循环末尾有一个分号。

改变这个 --> for(var i=0; i<fruitList.length; i++);

到此 --> for(var i=0; i<fruitList.length; i++){for(var i=0; i<fruitList.length; i++)

编辑注意事项: 将变量移出 for 循环并分配 innerHTML 或者您可以使用 textContent 到循环外的变量。然后在 for 循环中,将创建的 li 项附加到 ul 父项。

const userInput = prompt('Which fruit would you like?');
const fruitList = ["banana", 'strawberries', "mango"];
const fruits = document.getElementById('list');
const userFruit = document.createElement('li')
userFruit.innerHTML = userInput;

for (let i = 0; i < fruitList.length; i++) {
  if (userInput === fruitList[i]) {
    alert("Sorry, we are out of " + userInput);
  } else {
    fruits.append(userFruit);
  }
}  
<ul id="list"></ul>

这是因为它将您的条目与数组中的所有水果进行比较,所以只要没有太多,它就会将其添加到列表中。您可以改为使用 includes 方法来检查数组中元素的存在。

  var userInput = prompt('Which fruit would you like?');

  var fruitList = ["banana", 'strawberries', "mango"];

  if(fruitList.includes(userInput)) {
    alert("Sorry, we are out of " + userInput);
  }
  else {
    var userFruit = document.createElement('li');
    userFruit.textContent = userInput;
    var fruits = document.getElementById('list');
    fruits.appendChild(userFruit);
  }
 <div id="list"></div>