简体   繁体   English

在forEach回调中访问变量

[英]Accessing variable inside of forEach callback

I want to access a variable whose purpose is to aggregate records seen so far inside of the callback provided to forEach. 我想访问一个变量,其目的是聚合到目前为止提供给forEach的回调中看到的记录。 Something like this: 像这样:

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)
    );
}

Why shouldn't this work? 为什么不行呢?

You don't need to use this to refer to the array aggregate_val . 您不需要使用this来引用数组aggregate_val Try this code: 试试这个代码:

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