目录
在子函数中使用带有闭包的 concat 方法
javascriptarraysscopeclosures
浏览量:61
编辑于:2023-04-09 19:54:31

我想在子函数的作用域内使用,而不是推送,然后在作用域链的更高位置访问它。.concat

我这里有一个简单的函数,用于在通过正则表达式函数运行文件以过滤掉某些文件名和文件类型后列出目录中的文件。以下函数适用于 .push array 方法,但如果我尝试使用 .concat,它会返回一个空数组

fs.readdir('./schema', function(err,files){
  var filelist = [];
  if(err)
    throw err;
  else{
    var index = files.length;
    while(index>0){
      filelist.concat(isNOTswapfile(files[index]));
      index--;
      }
    console.log(filelist)
    }
  }
)

返回一个空数组[]

欢迎和感谢帮助。

解决方案:

concatreturns you a new Array back. So unless you reassign the variable back, it will just remainfilelist``[]

while(index>0){
  filelist = filelist.concat(isNOTswapfile(files[index]));
  index--;
}
console.log(filelist)

should work just fine.

You can read more on MDN Array.prototype.concat