未捕获的TypeError:无法读取未定义的属性“数量”

时间:2015-08-12 06:53:22

标签: javascript

我有一个功能

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中,它工作正常。当它进入辅助函数时它会产生这样的错误。我做错了什么?

1 个答案:

答案 0 :(得分:-1)

  1. 将'arr'替换为函数'EditQuantity'中的全局数组'foodarray'。
  2. 目前,只有当getindex = -1不正确时才会将元素添加到foodArray中。这将导致foodArray永远不会超过1个元素。
  3. 要修复它,代替'else'在调用EditQuantity方法之前使用if(getindex!= - 1)。