Javascript:数组的值在从其他函数引用后消失

Javascript:数组的值在从其他函数引用后消失,javascript,arrays,Javascript,Arrays,我目前尝试使用javascript构建一个表单,它有两个功能: 1) 向列表动态添加元素 2) 通过点击按钮识别某个元素(例如,具有最高值) 请参阅(我想将图片直接添加到我的帖子中,但我缺乏声誉-因此这里是它们的链接): 第一个功能可以正常工作(请参见上面添加的安装)。第二个没有。我的计划如下: 1) 当一个元素被添加到列表中时,我也会将它作为类“installation”的对象推送到数组installations=[] 2) 当我单击“标识最长持续时间”时,我在installations数组

我目前尝试使用javascript构建一个表单,它有两个功能:

1) 向列表动态添加元素

2) 通过点击按钮识别某个元素(例如,具有最高值)

请参阅(我想将图片直接添加到我的帖子中,但我缺乏声誉-因此这里是它们的链接):

第一个功能可以正常工作(请参见上面添加的安装)。第二个没有。我的计划如下:

1) 当一个元素被添加到列表中时,我也会将它作为类“installation”的对象推送到数组installations=[]

2) 当我单击“标识最长持续时间”时,我在installations数组上迭代map函数(并将最高值作为警报输出)

不幸的是,当我从另一个函数调用安装数组时,它是空的

  • 从表单中获取值
  • 向DOM添加值,调用另一个函数向数组添加值
  • 安装的类定义
  • 将安装添加到安装阵列
  • 当我调用createInstallation()函数中的summary函数进行测试时(在调用addInstallation()之后),一切正常;将显示installations数组的第一个元素:

    alert(installations[0].summary());
    
    见:

    当我从“Identify Longest”按钮的事件侦听器调用summary函数时,安装数组突然变为空,即使我在前一秒添加了一个元素(应该添加到安装数组中)

    见:

    恐怕这是一个范围问题;但我不知道如何修复它。 感谢您的帮助:-)

    非常感谢

    从表单中获取值
    var instStorage=document.getElementById(“instStorage”)

    这是没有发生的事情
    getElementById()
    按id而不是其值获取元素。
    假设
    instStorage
    和friends是
    input
    元素(很遗憾,没有显示),您可能需要更改代码以实际获取它们的:


    数组是对象,如果在函数中修改对象数组,则会修改原始数组。再次调试代码。@thanhtrong您能详细说明一下吗?
    
    const createInstallation = () =>  {
    
        ... (working code to add vars from 1) to list element in DOM)... 
        addInstallation(); // calling another function to add installation to installations array
    
    }
    
    
    
    class installation {
        constructor(storage, masse, price, discharge) {
            this.storage = storage;
            this.masse = masse;
            this.price = price;
            this.discharge = discharge; 
        }
        ... (getter functions here) ...
    
        summary = () => {
            return `Installation Specs: Storage ${this.getStorage()}, 
            Mass ${this.getMasse()}, Price ${this.getPrice()} and Discharge 
            Rate
            ${this.getDischarge()}`;
    
        }
    
    }
    
    const addInstallation = () => {
    
        installations.push(new installation(instStorage, instMasse, instPrice, instDischarge));
        (...)
    
    }
    
    alert(installations[0].summary());
    
    var instStorage = document.getElementById("instStorage").value;
    var instMasse = document.getElementById("instMasse").value;
    var instPrice = document.getElementById("instPrice").value;
    var instDischarge = document.getElementById("instDischarge").value;