我有一个功能
var foodArray = [] // this global variable arr contains list of object with property 'name' and 'quantity'.
function x (){
$('#menu-list button').click(function(){
//judge whether a button is add or minus
var type = $(this).attr('name');
//find current minus button element
var minus = $(this).closest('.food-edit').find('.minus');
//find current item's sales number element
var nSales = $(this).closest('.food-edit').find('.num-sales');
//conver current item's sales to a number
var num_Sales = Number(nSales.text());
//find food attributes
var foodNameStr = $($(this).closest('.food-detail').find('.food-name')).text();
var foodPrice = $($(this).closest('.food-detail').find('.food-price-num')).text();
var foodPrice_Num = parseFloat(foodPrice);
//take a food ID in DB
var foodID = $(this).closest('.food-detail').attr('id');
var getIndex = FindIt(foodID,foodArray);
if (type == "add") { //add a food into basket
minus.show();
TotalOperation(type,foodPrice_Num);
if ( getIndex == -1) {
var foodObj = {};
//add a new object
foodObj.ID = foodID;
foodObj.name = foodNameStr;
foodObj.price = foodPrice_Num;
foodObj.quantity = 1;
foodArray.push(foodObj);
nSales.text("1");
}
else {
EditQuantity(nSales,getIndex);// I get a index from previous code and pass to this function.And before I call this function. The arr already has couple objects for sure.
}
}
}
function EditQuantity(ns,index){
arr[index].quantity++;
....
}
当执行EditQuantity时,它会给我一个错误Uncaught TypeError:无法读取未定义的属性'quantity'。 但是如果我把arr [index] .quantity ++;直接在函数x中,它工作正常。当它进入辅助函数时它会产生这样的错误。我做错了什么?
答案 0 :(得分:-1)
要修复它,代替'else'在调用EditQuantity方法之前使用if(getindex!= - 1)。