前言
for in 和 for of 的基本用法
一、for in
1.数组
const arr = ['a', 'b', 'c', 'd'];
arr.name = 'NAME'
for (const i in arr) {
console.log(i);
}
//0 1 2 3 name 返回每个元素的索引
2.对象
const obj = {a: 'A', b: 'B', c: 'C', d: 'D'}
for (const i in obj) {
console.log(i);
}
//a b c d 返回每个元素的键名
二、for of
1.数组
const arr = ['a', 'b', 'c', 'd'];
arr.name = 'NAME'
for (const i of arr) {
console.log(i);
}
//a b c d 只返回索引是数字的元素
2.对象
//对于普通的对象,for of 循环不能直接使用,会报错
const obj = {a: 'A', b: 'B', c: 'C', d: 'D'}
for (const i of obj) {
console.log(i);
}
//Uncaught TypeError: obj is not iterable
总结
for in 循环适合对象,for of 循环适合数组