简体   繁体   English

javascript变量的全局和局部范围混淆

[英]javascript variable global and local scope confusion

$http({
    method: 'GET',
    url: '../URL'
}).
success(function(data, status, headers, config) {               
    items = data;
})

if(items > 0){
// do something
}

items is not defined in my case. 我的情况下未定义items I wonder I assigned data into items which with no var, so it's a global variable. 我想知道我是否将数据分配给没有var的项目,所以它是一个全局变量。 I also tried declare items = "" in global scope, the success scope doesn't overwrite and assign data into it. 我还尝试了在全局范围内声明items = "" ,成功范围不会覆盖并将数据分配到其中。

You are doing the manipulation of data obtained after the success callback outside the it, which should not be done. 您正在对成功回调之外的数据进行操作,而不应该这样做。

the below part 以下部分

if(items > 0){
// do something
}

where you manipulate the data obtained after the callback should be inside the success callback itself. 在回调之后处理的数据应该放在成功回调本身内部。 Making the variable global is not the way to achieve it as the code is not executed synchronous way. 使变量成为全局变量不是实现它的方法,因为代码不是同步执行的。

so the if condition 所以如果条件

if(items > 0){
// do something
}

will be getting executed even before the success callback get triggered. 甚至在触发成功回调之前都会被执行。 And hence the items variable will not be set by that time. 因此,此时将不会设置items变量。

your code should be like 您的代码应该像

success(function(data, status, headers, config) {               
    items = data;
    //do your manipulation here
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM