我正在尝试用新对象填充数组,但是我唯一得到的是-Uncaught TypeError:product不是构造函数
这是我的obj代码。构造函数:

function product(id, preview, colors, sizes, title, price) {
    this.id = id;
    this.preview = preview;
    this.colors = colors;
    this.sizes = sizes;
    this.title = title;
    this.price = price;
};


和循环代码:

    var products = [];
    for( i=0; i<db.length; i++) {
        var xyz = db[i];
        products[i] = new product( xyz.id, xyz.preview, xyz.colors, xyz.sizes, xyz.title, xyz.price );
    };


这是“ minfied”代码块示例:
https://jsfiddle.net/cujrfhyL/1/

-提前致谢。

最佳答案

如果products数组变量已经具有某种数据,则最好使用数组推送,以免覆盖其包含的数据



var product1 = { id: 6566, price: 3 };
var product2 = { id: 6566, price: 3 };
var product3 = { id: 6568, price: 3 };

var db = [ product1, product2 ];

function product(id, price) {
	this.id = id;
	this.price = price;
};

var products = [new product(product3.id,product3.price)];

function addProducts() {
	for( i=0; i<db.length; i++) {
		var xyz = db[i];
		products.push(new product( xyz.id, xyz.price ));
	}
  console.log(products)
};

addProducts();

关于javascript - 在循环内用新对象填充数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42395263/

10-13 04:40
查看更多