如何在 JavaScript 中实现该函数的闭包?

发布于 2024-10-03 02:30:21 字数 527 浏览 2 评论 0原文

昨晚,我用谷歌搜索了很多,但找不到解决我的问题的方法: 我有一个 for 循环,其中有一个函数,它只获取数组中的最新值。

所以,这是一个例子:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x in arrObjs) { //arrObjs = array of objects
  var g = arrObjs[x];

  // I can access properties of all "g" objects

  Routelousse.gen(function(res) {
    var pathern = res.pathern;
    g.routel.staviPather(pathern);

    MYOBJ.vehicles.push(g);
    alert(g.name); // during the loop I always get the LAST "g" object from "arrObjs"
  }, g.point);

}

Last night, I Googled a lot and couldn't find the solution for my problem:
I have a for loop with one function in it which gets me only the latest value from the array.

So, here is the example:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x in arrObjs) { //arrObjs = array of objects
  var g = arrObjs[x];

  // I can access properties of all "g" objects

  Routelousse.gen(function(res) {
    var pathern = res.pathern;
    g.routel.staviPather(pathern);

    MYOBJ.vehicles.push(g);
    alert(g.name); // during the loop I always get the LAST "g" object from "arrObjs"
  }, g.point);

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抠脚大汉 2024-10-10 02:30:21

它应该如下所示:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x=0; x<arrObjs.length; x++) {
  var g = arrObjs[x];

  (function(ig) {
    Routelousse.gen(function(res) {
      var pathern = res.pathern;
      ig.routel.staviPather(pathern);

      MYOBJ.vehicles.push(ig);
      alert(ig.name);
    }, ig.point);
  })(g);
}

在此,我们将当前的 g 作为不同的变量传递到该自执行函数中,而不是在函数中共享的 g您当前所处的位置(这不是块作用域)并且正在更改 for 循环的每一次传递。

另请注意 for 循环更改...您永远不应该使用 for...in 循环来迭代数组,请使用普通的 < code>for 循环。

It should look like this:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x=0; x<arrObjs.length; x++) {
  var g = arrObjs[x];

  (function(ig) {
    Routelousse.gen(function(res) {
      var pathern = res.pathern;
      ig.routel.staviPather(pathern);

      MYOBJ.vehicles.push(ig);
      alert(ig.name);
    }, ig.point);
  })(g);
}

In this we're passing the current g into that self-executing function as a different variable, rather than the g which is shared in the function you're currently in (this isn't block scope) and is changing each pass of the for loop.

Also note the for loop change...you should never use a for...in loop to iterate an Array, use a normal for loop for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文