我有一个 FileHelper 方法,它列出所有文件的名称并最终返回文件名:
import fs from 'fs';
import path from 'path';
class FileHelper {
static ListFiles() {
const fileDir = `${path.resolve()}/Specifications/`;
let files = fs.readdirSync(fileDir);
for (const file in files) {
console.log(file); // Prints filename correctly: 'petstore.json'
}
return files;
}
}
export default FileHelper;
但是,当我调用此方法并在 for 循环中再次打印它时,它会打印数组索引而不是值:
import FileHelper from './Helpers/FileHelper.js';
function main() {
try {
let specifications = FileHelper.ListFiles();
for (const specification in specifications) {
console.log(specification); // prints '0' instead of 'petstore.json'
}
}
catch(err) {
console.error(err);
}
}
main();
为什么在第二个for循环中不打印文件名?谢谢!
最佳答案
您看到该键的原因是因为 for...in
循环会迭代数组的键。
function main() {
try {
let specifications = FileHelper.ListFiles();
for (const key in specifications) {
const { [key]: value }= specifications;
// ^ the above line is equivalent to
// const value = specifications[key]
console.log(key, value);
}
}
catch(err) {
console.error(err);
}
}
查看 MDN documentation on for...in
,这解释了:
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
在对您的问题的评论中,Arun 链接到了一个出色的 StackOverflow 问题,该问题解释了实现目标的不同方法:why is using for...in for array iteration a bad idea
这些替代方法之一是 for...of
,看起来:
for (const specification of specifications) {
console.log(specification);
}
The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
此外,您可以使用 Array.prototype.forEach()
遍历数组。这是该方法:
specifications
.forEach((currentKey) => {
const { [currentKey]: specificationValue } = specifications;
console.log(currentKey, specificationValue);
})
或者你可以用老式的方式来做——使用 for
循环:
for (let i = 0; i < specifications.length; i++) {
console.log(i, specifications[i])
}
关于javascript - 返回的数组打印数组索引而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66289146/