簡體   English   中英

在數組中推送OBJ時未定義

[英]Undefined while pushing OBJ in Array

我正在嘗試為正在創建的網站在畫布中創建項目。 在使用對象和數組推送時,我使用了一個Alert來指示我數組中有什么,但它告訴我它是未定義的。 關於如何解決該問題或在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)”時,它沒有顯示名稱,而是顯示“無法讀取未定義的屬性'名稱'”錯誤 ,當我進行“ alert(product [0])”警告,但告訴我“未定義”

將您的代碼更改為以下代碼,您將產品分配給.push()

push()方法將新項目添加到數組的末尾,並返回新的長度。

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) 

push是一個函數,因此您需要使用parens push()進行調用。 您正在嘗試使用= ,所以它將不起作用。

在您的情況下,您應該執行以下操作: product.push( new products(tag,"name", price, "path/to/my/item", "description") );

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=control

首先,你應該像

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"));

並訪問該product[0]["Name"]屬性以供參考,請檢查JavaScript屬性訪問:點符號與方括號?

抱歉,此產品適用於此產品[0]。名稱也是如此,屬性名稱區分大小寫,因此將其更改為“名稱”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM