Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获类型错误:无法读取属性';数量';未定义的_Javascript - Fatal编程技术网

Javascript 未捕获类型错误:无法读取属性';数量';未定义的

Javascript 未捕获类型错误:无法读取属性';数量';未定义的,javascript,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'); //

我有一个函数

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中,它可以正常工作。当它转到辅助函数时,它会给出这样的错误。我做错了什么?

  • 将函数“EditQuantity”中的“arr”替换为全局数组“foodarray”
  • 当前,仅当getindex=-1不正确时,才会将元素添加到foodArray。这将始终导致foodArray从不包含超过1个元素
    要解决此问题,请在调用EditQuantity方法之前使用if(getindex!=-1)代替“else”。

    您也应该提供
    x
    函数,看起来您使用了一些异步操作。我认为这是因为quantity没有EditQuantity的作用域function@Puni听起来不错。但为什么它在函数x中有作用域?我认为您应该提供:
    函数EditQuantity(数组,索引)
    并调用x:
    EditQuantity(arr,index)
    arr[index]是否返回EditQuantity中的数据?。