Javascript全局变量未进入函数内部

Javascript global variable is not getting inside the function

本文关键字:函数 内部 全局变量 Javascript      更新时间:2023-09-26

我的页面中有以下javascript代码。

var data = {items: []};
var item_flag=false;
var check_flag=false;
var count = 0;
function add(){
    if(check_flag){
        //block A
    }else{
        data.items.push(
           {item: item, quantity: quantity, price: price}
        );
    }
}

在这里,我已经将变量数据声明为global。在函数add()中,我试图将值推送到else条件下的全局变量数据中。但我得到了错误,类型错误:数据未定义在if条件内部,变量数据是可访问的。

请帮我找到解决方案谢谢

试试这个。

function data() { this.items = []; }  
function items(item, quantity, price){   
   this.item= item;     
   this.quantity= quantity;    
   this.price= price;   
}
var Datas = new data();   //Global variable
function add(item, quantity, price){
    if(check_flag){
         //block A
    } else {
         Datas.items[Datas.items.length] = new items(item, quantity, price);
    }
}

工作小提琴