Rag*_*nis 13 javascript scope asynchronous for-loop node.js
var path;
for (var i = 0, c = paths.length; i < c; i++)
{
path = paths[i];
fs.lstat(path, function (error, stat)
{
console.log(path); // this outputs always the last element
});
}
Run Code Online (Sandbox Code Playgroud)
如何访问path传递给fs.lstat函数的变量?
gna*_*arf 27
这是使用.forEach()for循环来迭代值的完美理由.
paths.forEach(function( path ) {
fs.lstat( path, function(err, stat) {
console.log( path, stat );
});
});
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用像@Aadit建议的闭包:
for (var i = 0, c = paths.length; i < c; i++)
{
// creating an Immiedately Invoked Function Expression
(function( path ) {
fs.lstat(path, function (error, stat) {
console.log(path, stat);
});
})( paths[i] );
// passing paths[i] in as "path" in the closure
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10584 次 |
| 最近记录: |