简体   繁体   English

将参数传递给Array.forEach回调函数

[英]Passing arguments to Array.forEach callback function

someOperation.then(function(x) {
    things.forEach(function(thing) {
        //doing something with 'thing' that depends on variable 'x'
    });
});

In the code above, how can I make the variable 'x' available inside the callback function? 在上面的代码中,如何使变量'x'在回调函数中可用? Or do I have to go back to using a for loop in this case? 还是在这种情况下我必须回到使用for循环?

You can pass a "thisArg" as the second parameter to forEach so for instance: 您可以将“ thisArg”作为第二个参数传递给forEach,例如:

let x = { a: 123 };
things = ['foo', 'bar']
things.forEach(function(thing) {
    alert( this.a + thing );
}, x);

Might be helpful depending on what you are trying to do. 可能会有所帮助,具体取决于您要执行的操作。

It is available. 它是可用的。

 let x = { name: 'Mike' }; ['Hello', 'Goodbye'].forEach(function(greeting) { document.querySelector('pre').innerHTML += greeting + ', ' + x.name + '\\n'; }); 
 <pre></pre> 

What you're using here is known as a closure and is a commonly used feature of Javascript. 您在这里使用的是闭包 ,它是Javascript的常用功能。 Basically, any function has access to any other variable in it's parent scope. 基本上,任何函数都可以访问其父作用域中的任何其他变量。

 function log(msg) { document.querySelector('pre').innerHTML += msg + '\\n'; } var global = 'global'; function firstLevel(third) { var first = 'first'; // `global` is in the parent scope so we can access it log(global + ' -> ' + first); function secondLevel() { var second = 'second'; // Same thing with `first` here log(global + ' -> ' + first + ' -> ' + second); // This even works with passed in arguments log(global + ' -> ' + first + ' -> ' + second + ' -> ' + third); // We can even change closed over variables first = 'fourth?'; } secondLevel(); log(first); // Notice that `first` changed. } log(global); firstLevel('third'); // Notice how `third` is used in `secondLevel` 
 <pre></pre> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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