简体   繁体   中英

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. 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 . 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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