javascript内部变量的作用域

javascript内部变量的作用域,javascript,jquery,Javascript,Jquery,我有下面的代码示例,我正试着去理解它 $(document).ready(function () { test("load json", function () { length = 0; // length = 0 $.getJSON("plugins/form.json", function (data) { length = data.fields.length; // l

我有下面的代码示例,我正试着去理解它

        $(document).ready(function () {

        test("load json", function () {

            length = 0; // length = 0

            $.getJSON("plugins/form.json", function (data) {
                length = data.fields.length; // length = 4
            });

            ok(length == 4, "length = " + length.toString()); // length = 0? wtf?
        });
    });

$.getJSON运行时,“length”变量不会持久存在。我不知道是因为它是异步的还是因为变量超出了范围。

如果getJSON方法是异步运行的,那么ok(…行可能会在getJSON返回之前执行…因此长度将始终为0

你能不能不这样做

$.getJSON("plugins/form.json", function (data) {  
   var somelength = data.fields.length;  
   ok(somelength == 4, "length = " + somelength.tostring());  
});

这样,一旦getJSON返回了数据,它就会调用ok函数…

这不是因为作用域问题,而是因为这一行先运行

ok(length == 4, "length = " + length.toString());
在从JSON回调函数之前

function (data) {
    length = data.fields.length; // length = 4
}

您需要将
ok(length==4,“length=“+length.toString());
函数放在
$.getJSON的回调函数中,这是因为它是异步的

test("load json", function () {

     // executes first

     $.getJSON("plugins/form.json", function (data) {

         // executes last (that is, "sometime later")

     });

     // executes second

});
此外,除非您希望变量是全局变量,否则您应该第一次将变量声明为
var length

您应该进行异步测试,并且由于您正在使用,您可以使用该方法,在
getJSON
回调上进行断言,然后恢复以下测试:

$(document).ready(function () {

    test("load json", function () {
        stop();

        $.getJSON("plugins/form.json", function (data) {
            var length = data.fields.length;
            ok(length == 4, "length == " + length);
            start(); // resume tests
        });
    });
});
或者您可以使用该方法而不是
test
,该方法将隐式调用
stop

//...
asyncTest("load json", function () {

    $.getJSON("plugins/form.json", function (data) {
        var length = data.fields.length;
        strictEqual(length, 4, "length"); 
        //...
        start(); // resume tests
    });
});
//...
查看一个实例并查看源代码。

试试这个- $(文档).ready(函数(){


这是完全正确的,但还不够,测试运行程序需要暂停并恢复,检查我的和我不熟悉的QUnit…+1您的答案…但我的仍然提供了代码不工作的原因的答案(希望如此!)。。。
var length = 0; // length = 0
    test("load json", function () {

        $.getJSON("plugins/form.json", function (data) {
            length = data.fields.length; // length = 4
        });

        ok(length == 4, "length = " + length.toString()); // length = 0? wtf?
    });
});