繁体   English   中英

在JS / JSON函数中返回变量

[英]Returning variables inside JS / JSON functions

我试图了解JS中的JSON,回调等。 在下面的示例中,您将看到我在$ .getJSON的函数回调中。 然后,我进入getSomething()并期望它改变我的结果变量。 它会在功能范围内更改它,但是当我跳出该功能时不会更改它。

您将从2 console.log()看到第一个显示正确,而第二个显示不正确。 我确定问题的答案与通过返回变量有关。 回调,但有人可以启发
我 :)

谢谢!

码:

$.getJSON('/cart.js', function (cart, textStatus) {
  var result = '';
  result += 'Sample Stuff';
  StackOverflow.getSomething(param1, param2, function(a, b) {
    for(j=0; j < b.length; j++) {
      if (b.options[j] != 'Default Title') {
        if (a.options[j].name.indexOf("Color") > -1) {
          result += b.options[j].name;
          console.log(result); // <-- It comes out correct (Sample Stuff + b.options...)
        }
      }
    }
  });
  console.log(result); // <-- It comes out incorrect, just (Sample Stuff)
});

我猜StackOverflow.getSomething()运行一个AJAX请求吗? 因此,在AJAX请求完成之前,不会执行其回调(通过ab循环)中定义的内容。 发生的情况是,将触发StackOverflow.getSomething ,然后在代码末尾立即执行console.log(result) 到那时,尚未运行StackOverflow.getSomething的回调,并且尚未更新result 仅记录“样本内容”。 但是,当第二个console.log在( getSomething )AJAX请求之后在回调中执行时, result被更新并“正确”记录。

换句话说,执行顺序是这样

  1. result设置为“样本内容”
  2. StackOverflow.getSomething()使用附加的回调函数触发AJAX请求
  3. console.log(result)记录“样本内容”
  4. Ajax回调完成并触发其回调函数。 通过遍历ab相应地更新result
  5. 回调函数的console.log(result)记录的终值result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM