简体   繁体   English

JavaScript-空数组外部函数

[英]JavaScript - Empty Array Outside Function

I try to make a simple to do list but when I put let shoppingList = []; 我尝试做一个简单的清单,但是当我放let shoppingList = []; inside addItem() function it's not working. addItem()函数内部,它不起作用。 Why this is happening? 为什么会这样呢?

let shoppingList = [];

function addItem() {

  let Item = document.getElementById("item").value;
  let output = document.getElementById("output");
  let html = '';

  if (shoppingList.indexOf(Item) === -1) {
    shoppingList.push(Item);
  }

  for (var x = 0; x < shoppingList.length; x++) {
    html += (x + 1) + ". " + shoppingList[x] + "<br>";
  }

  output.innerHTML = html;

}

If you put your shoppingList array inside the function, it will create a new copy of an array - an empty one - every time the function is called, so every time the function is called it will work with a new array. 如果将shoppingList数组放入函数内,则每次调用该函数时都会创建一个数组的新副本-空副本,因此每次调用该函数时,它将与一个新数组一起使用。

If your array is global (defined outside of the function), as in your code sample, it keeps the added values between calls. 如果您的数组是全局的(在函数外部定义),则如代码示例中所示,它将在调用之间保留添加的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM