本文介绍了无法从其他函数(在全局范围内定义)中访问变量(数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用另一个函数中的变量(数组).我已经在全局范围内定义了它,但是它不起作用.

I'd like to use a variable (array) from another function. I already defined it in global scope, but it doesn't work..

这是我的代码,用于更好地理解:

Here is my code for better understanding:

var globalData = '';
var data = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data = globalData.name;

    console.log(data); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data); // just an empty line
    console.log(globalData); // UPDATE: works just fine
}

推荐答案

问题是回调函数中的变量data被遮盖了.

The problem is that the variable data is being shadowed within the callback function.

function(data) {

    globalData = data;
    data = globalData.name;

    console.log(data); // works just fine
...

因此function(data)建立了一个作用于该函数的局部变量.然后发生了奇怪的分配和重新分配的事情.您想相信自己正在操作data的全局版本,但是仅在处理作用域版本.

So function(data) established a local variable scoped to the function. Then the bizarre assign and reassign thing happens. You want to believe you are manipulating the global version of data but you are only dealing with the scoped version.

因此,必须将变量data传递给该函数.

So, the variable data must be passed to the function.

如果您想使用全局变量(不建议使用),您要做的就是将函数声明从(data)更改为其他标识符.

If you prefer to use the global (not recommended), all you have to do is change the function declaration from (data) to some other identifier.

这篇关于无法从其他函数(在全局范围内定义)中访问变量(数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:21