JavaScript变量全局和局部范围内的混乱 [英] javascript variable global and local scope confusion

查看:141
本文介绍了JavaScript变量全局和局部范围内的混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$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. I wonder I assigned data into items which with no var, so it's a global variable. I also tried declare items = "" in global scope, the success scope doesn't overwrite and assign data into it.

推荐答案

您正在做的是外成功回调后获得数据的操纵,这不应该做的。

You are doing the manipulation of data obtained after the success callback outside the it, which should not be done.

以下部分

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

在这里你操纵回调后得到的数据应该是成功回调本身中。使得全球的变量是不是实现它作为code未执行同步方式的方式。

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.

所以如果条件

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.

您code应该是这样

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

这篇关于JavaScript变量全局和局部范围内的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆