for in 遍歷的是當前索引,不適合遍歷陣列物件,返回的是陣列下標。(適合遍歷物件)
let arr = [
{name:'張三',age:18},
{name:'趙四',age:28},
{name:'王五',age:18}
]
for (const item in arr) {
console.log(item) // 0, 1, 2
console.log(arr[item]) // {name:'張三',..},{name:'趙四',..}{name:'王五',..}
}複製程式碼
for of 遍歷的是當前'鍵'值,適合遍歷陣列物件,返回的是陣列單個物件。(適合遍歷陣列物件)
// 例子同上
let arr = [
{name:'張三',age:18},
{name:'趙四',age:28},
{name:'王五',age:18}
]
for (const item of arr) { // 將in 改成 of
console.log(item) // 0, 1, 2
}複製程式碼