gpt4 book ai didi

javascript - 在 JS/JSON 函数中返回变量

转载 作者:行者123 更新时间:2023-11-30 06:48:44 26 4
gpt4 key购买 nike

我试图理解 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 在 AJAX 请求(getSomething)之后的回调中执行时,result 会“正确”更新和记录。

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

  1. result设置为“Sample stuff”
  2. StackOverflow.getSomething() 触发带有回调函数的 AJAX 请求
  3. console.log(result) 记录“示例内容”
  4. ajax 回调完成并触发其回调函数。 result 通过遍历 ab
  5. 进行相应更新
  6. 回调函数的console.log(result)记录result的最终值

关于javascript - 在 JS/JSON 函数中返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com