我正在尝试在 Canvas 中为我正在创建的网站创建项目。 在使用对象和数组推送时,我使用警报来指示数组中的内容,但它告诉我它是未定义的。 关于如何解决这个问题的任何建议,或者我在 JS 中做错了什么。 谢谢您
function products(tag, name, price, src, description){
this.Tag = tag;
this.Name = name;
this.Price = price;
this.Src = src;
this.Description = description;
}
var product = [];
product.push = new products(tag,"name", price, "path/to/my/item", "description");
当我使用所有真实信息执行此操作并执行“alert(product[0].name)”时,它不会显示它给我的名称”无法读取未定义的属性“名称”错误,当我执行“警报(产品[0])”时,会出现一个警报,但它告诉我“未定义”强>.
最佳答案
将您的代码更改为以下内容,您将把您的产品分配给 .push()
The push() method adds new items to the end of an array, and returns the new length.
product.push(new products(tag,"name", price, "path/to/my/item", "description"));
当您使用
时product.push = new products(tag,"name", price, "path/to/my/item", "description");
push
成为 product
的属性
function products(tag, name, price, src, description){
this.Tag = tag;
this.Name = name;
this.Price = price;
this.Src = src;
this.Description = description;
}
var product = [];
product.push(new products('just a tag',"Kevin", 'price', "path/to/my/item", "description"));
alert(product[0].Name)
关于javascript - 将 OBJ 插入数组时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120844/