[英]Javascript forEach returning “undefined” as object variables
[英]javascript variables returning as undefined
目前,我正在處理一些腳本,其背后的基本思想過程是,單擊一個鏈接,該鏈接會在籃子中生成和輸入,我目前在控制台中記錄了發送到籃子的內容。 當我單擊鏈接時,它會觸發additem()
函數,
function additem(desc,price,quantity)
{
var x = items.length - 1;
var found = (x == 0);
var y = new Item(desc,price,parseInt(quantity));
console.log(y);
var z = y;
while((x != 0) && (found == false))
{
z = items[x];
if(z != null)
{
if(z.M_desc == desc)
{
found = true;
}
else
{
x--;
}
}
else
{
x--;
}
}
if(found == false)
{
items[++numitems] = y;
}
else
{
items[x].M_quantity += quantity;
}
updatecart();
}
我在控制台中看到的是以下內容,
Item { M_desc="Item 2", M_price="10", M_quantity=1}
但是,當我單擊它時,我得到以下信息,
M_desc
"Item 2"
M_price
"10"
M_quantity
undefined
M_quantity如何設為1,然后在另一個控制台視圖中未定義?
=====編輯=====
我認為問題出在這里,我的JS代碼從這一行開始。
var items = new Array(2);
現在,我假設這會在我獲得[undefined, undefined]
之后立即運行console.log(items)
時創建一個新數組。
單擊鏈接使用以下代碼調用additem,
的HTML
<a class='product' rel='"+category[i].product[j].price+"' href=''>"+ category[i].product[j].description + "</a>
JS
$('.product').live("click",function(e){
additem($(this).text(), $(this).attr('rel'), 1);
e.preventDefault();
});
當items[x]
始終為null或未定義時,就會出現問題。 我不知道為什么。
您的updatecart函數幾乎同時被調用。 items[i].M_quantity = $('input[name="qty"]').val()
是有問題的行。 輸入為空,正在用undefined替換您的數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.