代码有一个问题,即在调用异步函数时变量会被写入.怎么修好?
码:
for (x in files) {
asynchronousFunction(var1, var2, function(){
console.log(x.someVaraible);
});
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,当调用asynchronousFunction中的回调函数时,x.files变量已更新为json数组文件中的下一个变量.我希望变量应该包含以前的值.
回调函数中的变量数不能更改,因此无法在回调函数中发送变量名.
Ala*_*ter 12
在javascript中使用'local'变量的问题是你的变量实际上有函数作用域,而不是块作用域 - 比如java和c#等
解决这个问题的一种方法是使用let具有块范围的方法,但目前只有firefox支持此方法.
所以这段代码只适用于firefox:
for (var x in files) {
// This variable has BLOCK scope
let file = files[x];
asynchronousFunction(var1, var2, function(){
console.log(file.someVaraible);
});
}
Run Code Online (Sandbox Code Playgroud)
对于其他浏览器,替代方法是使用闭包
for (var x in files) {
var file = files[x];
asynchronousFunction(var1, var2, (function(file){
return function() {
console.log(file.someVaraible);
};
})(file);
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用map/forEach,假设文件的数据类型是一个数组.
files.forEach(function(file) {
asynchronousFunction(var1, var2, function(){
console.log(file.someVaraible);
});
});
Run Code Online (Sandbox Code Playgroud)
如果它不是数组,那么你总是可以使用这种技术
[].forEach.call(files, function(file) {
asynchronousFunction(var1, var2, function(){
console.log(file.someVaraible);
});
});
Run Code Online (Sandbox Code Playgroud)
当然,更全面的写作方式
Array.prototype.forEach.call(files, function(file) {
// As before
Run Code Online (Sandbox Code Playgroud)
但我觉得[].forEach眼睛更好看
| 归档时间: |
|
| 查看次数: |
5673 次 |
| 最近记录: |