You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript使用push填充数组异常:每次生成新数组而非追加元素求助

问题:数组无法追加数据,每次点击按钮都会创建新数组

尝试通过JavaScript的push方法将HTML输入框中的数据填充到数组中,但控制台打印数组时发现,输入框的值并未追加到数组的下一个索引,反而每次点击提交按钮都会创建一个新数组。

相关代码

JavaScript代码

function addData() {

  // save the values from the inputs
  // display the calculation and the values on the screen and save it as a local storage
  let strategyValue, sharesValue, enterPriceValue, stopLossValue, profitPriceValue, stockNameValue;
  let soldArray = [];
  let boughtArray = [];


  // creating html nodes
  let breakLine = document.createElement("br");
  let stockStrategy = document.createElement("h2");
  let stockValue = document.createElement("h2");
  let stockPrice = document.createElement("h2");
  let stockStopLoss = document.createElement("h2");
  let stockProfitPrice = document.createElement("h2");
  let stockName = document.createElement("h2");

  // saveing the values into variblies
  strategyValue = document.getElementById('strategy').value; // strategy type
  sharesValue = document.getElementById('inputShares').value; // number of shares 
  enterPriceValue = document.getElementById('enterPrice').value; // bought share price
  stopLossValue = document.getElementById('stopLoss').value; // stop loss price
  profitPriceValue = document.getElementById('profitPrice').value; // sold price
  stockNameValue = document.getElementById('stockName').value; // stock name 

  // append value to the html node 
  stockStrategy.innerHTML = strategyValue;
  stockValue.innerHTML = sharesValue;
  stockPrice.innerHTML = enterPriceValue;
  stockStopLoss.innerHTML = stopLossValue;
  stockProfitPrice.innerHTML = profitPriceValue;
  stockName.innerHTML = stockNameValue;

  // i want to add the stockTitle append it to the div-result in the html node

  divResult = document.getElementById('divResult');

  let div = document.createElement("div");

  div.className = 'div-result'

  div.appendChild(stockName);
  div.appendChild(stockStrategy);
  div.appendChild(stockPrice);
  div.appendChild(stockStopLoss);
  div.appendChild(stockProfitPrice);
  div.appendChild(stockValue);
  div.appendChild(breakLine);

  divResult.append(div)

  // i want to push the value of the sold price into the sold array
  // also push the value of the bought price into the bought  array  

  soldArray.push(profitPriceValue);
  boughtArray.push(enterPriceValue);

  console.log(soldArray);
  console.log(boughtArray);
}

HTML代码

<div class="title">
  <h1>Power Tracker</h1>
</div>
<div class="div-main-inputs">
  <div class="div-inputs">
    <label>Stock Name</label>
    <input value="" type="text" class="input-stock" id='stockName'>
    <label>Choice Strategy</label>
    <input value="" type="text" class="input-strategy" id='strategy'>
  </div>
  <div class="div-secondInputs">
    <label>Bought Price</label>
    <input value="" type="number" class="input-enter" id='enterPrice'>
    <label>Stop Loss Price</label>
    <input value="" type="number" class="input-stop-loss" id='stopLoss'>
    <label>Profit Price</label>
    <input value="" type="number" class="input-profit-price" id='profitPrice'>
    <label>Choice Shares</label>
    <input value="" type="number" class="input-shares" id='inputShares'>
  </div>
  <button class="btn-submit" onclick="addData()">Submit</button>
</div>
<div class="div-result0" id='divResult'>
</div>

解决方案

问题根源

soldArray和boughtArray是在addData函数内部声明的局部变量,每次点击按钮调用addData时,这两个数组都会被重新初始化为空数组,因此每次push后数组中只有当前输入的值,无法实现追加。

修改方法

将数组声明移到函数外部,作为全局变量,这样数组只会初始化一次,每次点击按钮都会往同一个数组中追加数据:

// 将数组声明移到函数外部
let soldArray = [];
let boughtArray = [];

function addData() {

  // save the values from the inputs
  // display the calculation and the values on the screen and save it as a local storage
  let strategyValue, sharesValue, enterPriceValue, stopLossValue, profitPriceValue, stockNameValue;


  // creating html nodes
  let breakLine = document.createElement("br");
  let stockStrategy = document.createElement("h2");
  let stockValue = document.createElement("h2");
  let stockPrice = document.createElement("h2");
  let stockStopLoss = document.createElement("h2");
  let stockProfitPrice = document.createElement("h2");
  let stockName = document.createElement("h2");

  // saveing the values into variblies
  strategyValue = document.getElementById('strategy').value; // strategy type
  sharesValue = document.getElementById('inputShares').value; // number of shares 
  enterPriceValue = document.getElementById('enterPrice').value; // bought share price
  stopLossValue = document.getElementById('stopLoss').value; // stop loss price
  profitPriceValue = document.getElementById('profitPrice').value; // sold price
  stockNameValue = document.getElementById('stockName').value; // stock name 

  // append value to the html node 
  stockStrategy.innerHTML = strategyValue;
  stockValue.innerHTML = sharesValue;
  stockPrice.innerHTML = enterPriceValue;
  stockStopLoss.innerHTML = stopLossValue;
  stockProfitPrice.innerHTML = profitPriceValue;
  stockName.innerHTML = stockNameValue;

  // i want to add the stockTitle append it to the div-result in the html node

  divResult = document.getElementById('divResult');

  let div = document.createElement("div");

  div.className = 'div-result'

  div.appendChild(stockName);
  div.appendChild(stockStrategy);
  div.appendChild(stockPrice);
  div.appendChild(stockStopLoss);
  div.appendChild(stockProfitPrice);
  div.appendChild(stockValue);
  div.appendChild(breakLine);

  divResult.append(div)

  // i want to push the value of the sold price into the sold array
  // also push the value of the bought price into the bought  array  

  soldArray.push(profitPriceValue);
  boughtArray.push(enterPriceValue);

  console.log(soldArray);
  console.log(boughtArray);
}

额外建议

如果不想使用全局变量,可以考虑将数组存储在localStorage中,实现页面刷新后数据不丢失:

function addData() {
  // 从localStorage读取数组,不存在则初始化为空数组
  let soldArray = JSON.parse(localStorage.getItem('soldArray')) || [];
  let boughtArray = JSON.parse(localStorage.getItem('boughtArray')) || [];

  // ... 原有代码 ...

  soldArray.push(profitPriceValue);
  boughtArray.push(enterPriceValue);

  // 将数组存回localStorage
  localStorage.setItem('soldArray', JSON.stringify(soldArray));
  localStorage.setItem('boughtArray', JSON.stringify(boughtArray));

  console.log(soldArray);
  console.log(boughtArray);
}

内容的提问来源于stack exchange,提问作者Dor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:20:20