javascript - 为什么 .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"
}]
提前致谢!
解决方案
你应该使用“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
推荐阅读
- visual-studio-code - Plotly express 在 vscode jupyter 中不显示图像
- node.js - MongoDB ObjectId(string) 生成一个新的 Id 而不是代表 id 的给定字符串
- c++ - 成员函数特化中的循环依赖......“特化之前的实例化”
- sql - PostgreSQL全文搜索没有找到它应该找到的一些单词
- python - 如何找到最近的 AWS 区域来部署云应用程序
- selenium-grid - 是否可以使用 selenium 网格设置运行空手道 UI 测试
- c++ - deleting shared_ptrs from unordered_map when deleting shared_ptr from vector ( simulatiously)
- angular - Angular 和 Spring-Boot (Spring Security):服务 http.post 调用上的 .subscribe() 无法正常工作
- node.js - TypeError:Nodejs.getName 不是函数
- ios - 为文件提供程序扩展附加调试器