【问题标题】:getJSON scope and variable definitionsgetJSON 范围和变量定义
【发布时间】:2015-09-09 00:44:06
【问题描述】:

我无法理解为什么我的代码运行不正常。即,我很困惑为什么在函数运行后foo.bar 是undefined,但在函数中定义。

function async(foo, n) {

  console.log("getting value number: " + n);

  $.getJSON("database.json", function(data) {
    foo.bar = data.value[n];
    console.log(foo.bar); // this works
  });
}

//////////////////////////////////////////////////////////

var foo = new String();

async(foo, 0);

console.log(foo.bar); // doesn't work

console 输出以下内容:

>getting stop number: 0
>undefined
>defined

【问题讨论】:

    标签: javascript jquery json getjson


    【解决方案1】:

    $.getJSON 将异步运行回调。也就是说它是非阻塞的,只有在收到响应后才会运行回调,这是在所有其余代码都运行之后。

    【讨论】:

    • 是否有正确的方法来编写我的代码?也就是说,以一种定义 foo.bar 的方式编写它而不同步运行 getJSON?
    • 正确的做法是在回调中处理响应。
    【解决方案2】:

    更新:

    function async(foo, n) {
            // «foo» is a parameter that only exists in the context of the function «async()», the same way for «n».
    
            console.log("getting value number: " + n);
    
            $.getJSON( "database.json", function(data) {
            // Dynamically, the Javascript engine foo is interpreted as an object, because your result is an object with a specific value.
                foo.bar = data.value[n];
            // You're overwriting foo parameter with the new result. (data.value[n]).
    
            // Then
                console.log(foo.bar);    // this works!
            });
    }
    

    还有:

    var foo = new String();
    

    foo 是 String 的原始对象。

    当你这样做时:

    console.log(foo);
    

    你在控制台中得到这个:

    String {length: 0, [[PrimitiveValue]]: ""}
    

    在这一行:

    async(foo, 0);
    

    您正在使用 String 的原始对象和 «0» 作为参数调用异步函数。

    更新了适当的解决方案:

    默认情况下,依赖于 异步或同步请求,将完成与 请求完成时所需的值。这取决于 来自服务器的响应。

    你需要等待服务器的响应来分配一个变量 与最终值,然后显示它。

    你应该试试这个:

    var foo = {}; // Declare an object.
    foo.bar; // Add bar attribute in this object.
    
    
    function async(n) {
        console.log("getting value number: " + n);
    
        $.getJSON("database.json", function (data) {
            foo.bar = data.value[n]; // foo.bar has a new value from the Asynchronous request.
            printResult(); // Call printResult function to print in the console.
        });
    }
    
    function printResult() {
        console.log(foo.bar);
    }
    
    
    // Execute async function.
    async(0);
    

    Demo

    【讨论】:

    • 您对如何“修复”这个问题或如何正确编写它有什么建议吗?
    • 是的,当然,我刚刚用解决方案更新了我的答案。
    猜你喜欢
    • 2012-03-30
    • 1970-01-01
    • 2011-09-20
    • 2013-01-17
    • 1970-01-01
    • 2021-08-18
    • 2013-01-16
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多