将参数传递给 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'
});
});
在上面的代码中,如何让变量 'x' 在回调函数中可用?还是在这种情况下我必须返回使用 for 循环?
可用。
let x = {
name: 'Mike'
};
['Hello', 'Goodbye'].forEach(function(greeting) {
document.querySelector('pre').innerHTML += greeting + ', ' + x.name + '\n';
});
<pre></pre>
您在这里使用的是 closure,是 Javascript 的常用功能。基本上,任何函数都可以访问其父作用域中的任何其他变量。
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>
您可以将 "thisArg" 作为第二个参数传递给 forEach,例如:
let x = { a: 123 };
things = ['foo', 'bar']
things.forEach(function(thing) {
alert( this.a + thing );
}, x);
可能会有所帮助,具体取决于您要执行的操作。
someOperation.then(function(x) {
things.forEach(function(thing) {
//doing something with 'thing' that depends on variable 'x'
});
});
在上面的代码中,如何让变量 'x' 在回调函数中可用?还是在这种情况下我必须返回使用 for 循环?
可用。
let x = {
name: 'Mike'
};
['Hello', 'Goodbye'].forEach(function(greeting) {
document.querySelector('pre').innerHTML += greeting + ', ' + x.name + '\n';
});
<pre></pre>
您在这里使用的是 closure,是 Javascript 的常用功能。基本上,任何函数都可以访问其父作用域中的任何其他变量。
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>
您可以将 "thisArg" 作为第二个参数传递给 forEach,例如:
let x = { a: 123 };
things = ['foo', 'bar']
things.forEach(function(thing) {
alert( this.a + thing );
}, x);
可能会有所帮助,具体取决于您要执行的操作。