javascript - 如何以 JSLint 认可的方式重写这个 while 循环?

标签 javascript node.js jslint

查看来自:https://github.com/jprichardson/node-fs-extra#walk 的“Streams 2 & 3(拉)示例”

var items = [] // files, directories, symlinks, etc
var fs = require('fs-extra')
fs.walk(TEST_DIR)
  .on('readable', function () {
    var item
    while ((item = this.read())) {
      items.push(item.path)
    }
  })
  .on('end', function () {
    console.dir(items) // => [ ... array of files]
  })

最新版本的 JSLint 关于 while 的提示:

Unexpected statement '=' in expression position.
                while ((item = this.read())) {
Unexpected 'this'.
                while ((item = this.read())) {

我正在尝试弄清楚如何以 JSLint 认可的方式编写它。有什么建议吗?

(注意:我知道这段代码中还有其他 JSLint 违规行为……我知道如何解决这些问题……)

最佳答案

如果你真的像 Douglas Crockford(JSLint 的作者)一样对编写这段代码感兴趣,你会使用递归而不是 while 循环,因为在 ES6 中有尾调用优化。

var items = [];
var fs = require("fs-extra");
var files = fs.walk(TEST_DIR);
files.on("readable", function readPaths() {
    var item = files.read();
    if (item) {
        items.push(item.path);
        readPaths();
    }
}).on("end", function () {
    console.dir(items);
});

关于javascript - 如何以 JSLint 认可的方式重写这个 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371041/

相关文章:

javascript - 如何使用 ScrollMagic 固定和重叠多个元素?

javascript - WebSync Publish ClientId 变为零

mongodb - 为什么这个 Node.js 插件 Mongoose 不起作用?我遵循了所有指示

javascript - 为什么当版本正确时 Yarn 说 "Found incompatible module"?

node.js - Sublime 2 text - 在保存 .js 文件期间构建

javascript - 使用 jshint 遵守最大长度设置

javascript - 错误类型错误 : Cannot convert undefined or null to object

javascript - D3 JS - 包含 SVG 矩形的组在拖动时无法顺利转换

javascript - 推荐的 jslint 配置?

javascript - 组合 'var' 语句