javascript - 为什么我的循环只循环一次,即使有 3 个项目?

标签 javascript node.js ecmascript-6

以下代码循环遍历文件并输出它们的名称和一些 xhtml:

#! /usr/bin/env node

var fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/')

console.log(files.length)

var manifest = function() {
  for (let i = 0, l = files.length; i < l; ++i) {
    let contents = fs.readFileSync(__dirname + '/files/' + files[i], 'utf8')
    return `<item href="${files[i]}.html" id="html30" media-type="application/xhtml+xml"/>\n`
  }
}

console.log(manifest())

输出是这样的:

alex@alex-K43U:~/node/m2n3/bin$ node content.js
<item href="foo1.txt.html" id="html30" media-type="application/xhtml+xml"/>

这很奇怪,因为有三个文件。 console.log(files.length) 输出:

alex@alex-K43U:~/node/m2n3/bin$ node content.js
3

可能是什么问题?

最佳答案

正如我在评论中提到的,return 将立即退出您的 manifest() 调用,并找到第一个值。

对于更多 ES6 功能来说,这似乎是一个很好的用例:

// Enable const/let inside of node
"use strict";

const fs = require('fs'),
    files = fs.readdirSync(__dirname + '/files/')

// Create a generator function so that the caller can iterate using for..of
const manifests = function*() {
  // for..of to iterate array contents directly, no need for a counter
  for (let fileName of files) {
    // Nothing actually done with contents - do you need it?
    let contents = fs.readFileSync(__dirname + '/files/' + fileName, 'utf8');
    // Use 'yield' instead of 'return' to say that we're done with this
    // iteration, the caller can choose to either exit or continue to the next
    yield `<item href="${fileName}.html" id="html30" media-type="application/xhtml+xml"/>
`; // Newline will be parsed by the template string literal
  }
}

// for..of to iterate our manifests
for(const manifestXml of manifests()) {
  console.log(manifestXml);
}

关于javascript - 为什么我的循环只循环一次,即使有 3 个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155679/

相关文章:

javascript - 引用错误 : process is not defined when requiring Shelljs in ReactJS

javascript - 如何获取浏览器视口(viewport)尺寸?

javascript - 从 Word 复制时从剪贴板数据中删除项目符号

javascript - 使用 Ajax 监控表单失败

node.js - 如何在 JEST 测试用例中检查全局获取的响应

javascript - 比较断言中的函数输出类型

javascript - React 16 Modal 表单更新操作

javascript - Jquery:无法让动画工作

node.js - 连接错误: Failed to connect in mssql in nodeJS

node.js - userId是全局唯一标识符吗?