【问题标题】:How to access variable outside of a nested each() function?如何访问嵌套 each() 函数之外的变量?
【发布时间】:2014-02-18 03:19:19
【问题描述】:

我希望能够在函数之外访问 嵌套 each() 函数的值。

我的方法是:

  • 在函数外定义变量,
  • 在函数内更新,
  • 能够在函数之外访问更新的值。

但这不起作用:

jsFiddle

http://jsfiddle.net/rwone/ESXB4/

jQuery

var my_array = [{"check": "tom", "nested_array": [{"nested_array_2": ["1", "2"], "name": "tom", "image": "one.jpg"}, {"nested_array_2": ["1", "2"], "name": "bob", "image": "two.jpg"}]}];

var check = my_array[0].check;

var desired_value = "hello";

$.each(my_array, function (obj, v) {
    $.each(v.nested_array, function (i, value) {
        if (value.name == check) {
            var desired_value = value.image;
            alert(desired_value);  // this returns `one.jpg`, the variable has been updated.  
        }
    });
});

//alert(desired_value); // this alerts 'hello',  the variable has not been updated.  

如果上述方法错误,谁能演示如何访问嵌套each() 循环的返回值?

编辑:我应该说,我在任何阶段都谨慎使用全局变量,因为这可能会在以后的应用程序中引起问题。

编辑 2: 我认为在函数中使用全局 var 会永远定义变量(除非再次全局定义),但它似乎不是:

var desired_value = "hello";

$.each(my_array, function (obj, v) {
$.each(v.nested_array, function (i, value) {
if (value.name == check) {
desired_value = value.image; // 'global'
alert(desired_value);  // this returns `one.jpg`, the variable has been updated.  
}
});
});

alert(desired_value); // this alerts 'one.jpg',  the variable has been updated.  

var desired_value = "new value";

alert(desired_value); // this alerts 'new value'

更新的 jsFiddle

http://jsfiddle.net/rwone/ESXB4/2/

【问题讨论】:

  • 这是非常基本的javascript。从你最里面的desired_value 中删除var,所以它变成:desired_value = value.image;

标签: jquery each


【解决方案1】:

您正在使用 var desired_value = value.image; 从外部范围遮蔽 desired_value。这将在循环函数中创建一个名为 desired_value 的局部变量。你应该在这里删除var

【讨论】:

  • 这是第一个答案,所以我应该接受它。您能否提供更多信息,说明为什么在函数中“全局”分配变量不会用var 覆盖以后的分配 - 请参阅更新的帖子和小提琴。
  • 非常感谢,这非常有用"If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it)" (source)
  • 4 年后,这是完美的!谢谢@AlexanderTokarev
【解决方案2】:

更新FIDDLE

        var my_array = [{"check": "tom", "nested_array": [{"nested_array_2": ["1", "2"], "name": "tom", "image": "one.jpg"}, {"nested_array_2": ["1", "2"], "name": "bob", "image": "two.jpg"}]}];

var check = my_array[0].check;

var desired_value = "hello";

$.each(my_array, function (obj, v) {
$.each(v.nested_array, function (i, value) {
if (value.name == check) {
desired_value = value.image;  // here changes was made
alert(desired_value);  
}
});
});

alert(desired_value); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2019-04-04
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多