[英]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.