【问题标题】:How can I rewrite this while loop in a JSLint-approved way?如何以 JSLint 认可的方式重写这个 while 循环?
【发布时间】:2023-03-26 23:18:01
【问题描述】:

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

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]
  })

关于while的最新版JSLint投诉:

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

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

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

【问题讨论】:

  • 您的意思是使用== 进行比较吗?
  • 如果你在比较不应该是while ((item === this.read()))
  • @A.J 不,这是一个期望在这里返回真实值的赋值。而 JSLint 不喜欢这些,在一组表达式中发生了太多事情。
  • 我认为 OP 依靠 read() 在没有更多可读数据时返回一个虚假值。
  • 我建议使用可配置的 ESLint,而不是 JSLint。

标签: javascript node.js jslint


【解决方案1】:

如果你真的有兴趣像 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);
});

【讨论】:

  • 感谢您的回复。您将如何摆脱 this
  • @boozedog 更新,删除 this
猜你喜欢
  • 1970-01-01
  • 2020-11-21
  • 2021-02-12
  • 1970-01-01
  • 2014-09-03
  • 2020-03-05
  • 2021-06-17
  • 2021-02-18
  • 2016-03-11
相关资源
最近更新 更多