首页 > 解决方案 > 每次运行函数时如何将对象添加到数组中?

问题描述

我正在尝试编写一个系统,每次输入新数据并按添加时,它都会创建一个对象,并将该对象添加到数组中。但我不确定如何将新对象添加到数组中。另外我不确定为什么我的代码不在黄色框中。


var products = [];



class Product {

    constructor(productname, cost, quantity){
        this.productname = productname;
        this.cost = cost;
        this.quantity = quantity;
    }

}


function addProduct(){

    var productname = document.getElementById('productName').value;
    var cost = document.getElementById('cost').value;
    var quantity = document.getElementById('quantity').value;

    tbody += '<tr><td>' + productname + '</td><td>' + cost + '</td><td>' + quantity + '</td><td>' + test + '</td><tr>';

      document.getElementById('tablebody').innerHTML = tbody;

      product();

//adding product to array

 function product(){

        products = new Product(productname, cost, quantity);
}
}

'''

标签: javascriptarraysobject

解决方案


products当你调用product- 使用- 时你正在覆盖push- 也将变量传递给,product否则你会得到一个错误:

    product(productname, cost, quantity);

}

function product(productname, cost, quantity) {
    products.push(new Product(productname, cost, quantity));
}

addProducts还要用大括号关闭你的函数:

    document.getElementById('tablebody').innerHTML = tbody;

    product();

}

推荐阅读