[英]Creating an Array of Objects from an XML file - Javascript
我正在嘗試在 JavaScript 中創建一個對象數組,並從 XML 文件中填充每個對象。 XML 文件已在前一個函數中加載。 但是,當我嘗試推送新產品時,我在控制台中收到一個錯誤,提示 x[i] 未定義。
我的代碼是:
function CreateProductObject() {
function productObject(name, brand, price, info, material, photo) {
this.name = name;
this.brand = brand;
this.price = price;
this.info = material;
this.photo = photo;
}
var productArray = [];
var numOfProducts = CountProducts(productType);
console.log(productType + " needs to be Displayed: " + numOfProducts);
x = xmlDoc.getElementsByTagName(productType);
for (i = 0; i <= numOfProducts; i++) {
productArray.push(
new productObject(
x[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue,
x[i].getElementsByTagName("BRAND")[0].childNodes[0].nodeValue,
x[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue,
x[i].getElementsByTagName("INFO")[0].childNodes[0].nodeValue,
x[i].getElementsByTagName("MATERIAL")[0].childNodes[0].nodeValue,
x[i].getElementsByTagName("PHOTO")[0].childNodes[0].nodeValue,
),
);
console.log(productArray[i].name);
}
}
任何幫助表示贊賞。
您尚未聲明x
,因此它是未定義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.