javascript - 返回的数组打印数组索引而不是值

标签 javascript node.js arrays for-loop

我有一个 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();

enter image description here

为什么在第二个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/

相关文章:

javascript - 当我在整理我的 cordova 应用程序并重新启动它后尝试添加更多数据时,lokijs 丢失了集合中的数据库和数据

javascript - 如何按名称删除 Highcharts 中的系列

node.js - 如何在NPM任务中为node.js设置环境变量

Node.js 或 Express.js REST API 文档生成器

python - numpy 数组中的奇怪赋值

javascript - 异步 puppeteer 浏览器在几次迭代后断开连接

javascript - 如何将变量移出作用域?

javascript - 从 websocket 接收看似封装的 JSON。我该如何处理这种格式?

javascript求和多维数组

c++ - 只需要执行一个 free() 操作的 C 风格二维动态数组