我正在尝试编写一个系统,每次输入新数据并按添加时,它将创建一个对象并将该对象添加到数组中。但是我不确定如何向数组添加新对象。另外,我不确定为什么我的代码不在黄色框中。
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);
}
}
'''
答案 0 :(得分:1)
调用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();
}