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

时间:2015-12-08 12:17:09

标签: 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

可能是什么问题?

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

return语句会中断循环,您可以将值存储在数组中并让您的方法返回该数组。

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