【问题标题】:An array resets when I submit the second value当我提交第二个值时数组重置
【发布时间】:2020-06-08 18:54:53
【问题描述】:

当我向数组和 console.log 添加一个值时,第一个值被删除并且数组重新启动总是留下一个值。如何通过每次单击同一个按钮来添加多个值?

function calcBudget(){

    //expenseCostValue is an input in a form.     
    const expenseValue = expenseCostValue.value;
    const itemList = [];
    itemList.push(expenseValue); 
    console.log(itemList);

【问题讨论】:

    标签: javascript arrays forms


    【解决方案1】:

    您可能每次都在重新定义您的数组。将 const itemList = [] 放在 click 事件处理程序之外。只需在 click 事件处理程序中运行 itemList.push(expenseValue)

    【讨论】:

      【解决方案2】:

      你必须改变你的数组的范围

      function calcBudget() {
        const expenseValue = expenseCostValue.value;
        const itemList = []; // → remove the array
      
        console.log(itemList);
      }
      
      const itemList = []; // we declare it out of our function
      
      function calcBudget() {
        const expenseValue = expenseCostValue.value;
        itemList.push(expenseValue);
      
        console.log(itemList);
      }
      

      希望对我有所帮助

      【讨论】:

        猜你喜欢
        • 2016-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2020-10-21
        相关资源
        最近更新 更多