javascript - 将 OBJ 插入数组时未定义

标签 javascript arrays

我正在尝试在 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 的属性

enter image description here

 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/

相关文章:

javascript - 避免使用 jquery 对每个项目重复相同的代码

php - 在端口 8080 上运行的 Apache 会阻止 JavaScript 中的动态加载脚本吗?

javascript - 替代 (?!y) 但在一个词之前

javascript - 批处理文件打开多个 URL

arrays - 如何在 VBA 中声明数组变量?

ios - 删除具有重复键的对象

javascript - 将 JavaScript 数组转换为对象

java - 以数组形式跟踪田径运动时间

c - 给定数组中的最小奇数

c - 一次输出多个字符(包括ASCII)?