簡體   English   中英

在forEach回調中訪問變量

[英]Accessing variable inside of forEach callback

我想訪問一個變量,其目的是聚合到目前為止提供給forEach的回調中看到的記錄。 像這樣:

var myfn = function() {
    var aggregate_val = [];
    someObj.someFunction(
        arg1,
        arg2,
        (function() {
            ....
            some_array.forEach(function(e) {
                this.aggregate_val.push(e.some_property);
            }, this);
        }).bind(this)
    );
}

為什么不行呢?

您不需要使用this來引用數組aggregate_val 試試這個代碼:

var myfn = function() {
  var aggregate_val = [];
  some_array.forEach(function(e) {
    aggregate_val.push(e.some_property);
  });
  console.log(some_array) // I added this so you can see the value of some_array
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM