首页 > 解决方案 > 为什么 .forEach() 有效但 for 循环无效?

问题描述

目前正在学习 Node.JS 并制作一个基本的命令提示符笔记应用程序。在处理 listNotes 函数(旨在显示笔记的所有标题)时,我最初是这样开始的:

const notes = loadNotes() 
    for (let note in notes) {
        console.log(note.title)
    }

这给我留下了一个不确定的。

然而,

const notes = loadNotes()
    notes.forEach((note) => {
        console.log(note.title)
    })

给我留下了实际的笔记标题。

在这种情况下,forEach 和 for 循环有什么区别?

为了澄清起见,我的 loadNotes() 方法所做的只是读取一个 JSON 文件并将其解析为一个对象。如果文件不存在,则创建一个空数组

注意可以定义为:

Note[{
title: "string",
body: "string"
}]

提前致谢!

标签: javascriptnode.jsarraysfor-loopforeach

解决方案


你应该使用“of”而不是“in”

前任:

const notes = loadNotes() 
for (let note of notes) {
  console.log(note.title)
}

就像菲尔指出的那样,for..in将迭代索引。

例如,如果 notes 是一个数组:

const notes = loadNotes() 
for (let index in notes) {
  console.log(index)
}
// outputs are: 0,1,2, etc...
// You are doing something like: 1.title, 2.title
// 'title' is not a field of these numeric values, 
// so you are getting 'undefined' values

推荐阅读