相同:都可以用来遍历数组
不同:for of 是ES6开始有的,用来遍历值的,而 for in是用来遍历索引的,并且返回的索引是字符串型数字。
例:
let arr = ['A','B','C'];
for (let i in arr){
console.log(`i的值为:${i}, i的类型为:${typeof i}`);
}
for (let o of arr){
console.log(`o的值为:${o}, o的类型为:${typeof o}`);
}
// output
i的值为:0, i的类型为:string
i的值为:1, i的类型为:string
i的值为:2, i的类型为:string
o的值为:A, o的类型为:string
o的值为:B, o的类型为:string
o的值为:C, o的类型为:string
注意:
- console 的输出不是单引号,使用的是Tab键上方的 ` ,参考模板字符串
- i 的类型是字符串,如果需要比较大小,需要使用 Numbe(i)的方式进行转换
- 虽然 i 的类型是字符串,但是如果取数组的指定位置元素,使用arr[0]也可以做到,因为比较 1 == '1' 会返回true,使用时注意区分