我正在尝试编写一个系统,每次输入新数据并按添加键时,它都会创建一个对象,并将该对象添加到数组中。但我不确定如何将新对象添加到数组中。另外我不确定为什么我的代码不在黄色框中。
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);
}
}
'''
最佳答案
当您调用 product
时,您会覆盖 products
- 使用 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();
}
关于javascript - 每次运行函数时如何将对象添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61625154/