以下代码循环遍历文件并输出它们的名称和一些 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/