在JavaScript 中常用的两种遍历 for in 和 for of,先简单来理解它们的区别:
1. for in 是遍历 key
2. for of 是遍历 value
不过最近发现关于 for in 之前没注意到的一个特点:
对数组使用for in 遍历时,取到的索引值是 string 类型,而不是 number.
例如:
let array = ["A","B","C"];
for (let index in array) {
console.log(index + " : " + array[index]);
console.log("index type : " + typeof index);// string
if (index === 1) {
//Never goes here
}
console.log("index === 1 : " + (index === 1));// Always false
}
如果你在使用 for in 遍历一个数组的时候,期望通过“index === 1”来判断到达位置 1 时,那实际结果就会不如人愿了。
综上,如果要在 for in 中判断 index 到达位置 1,有两种方法:
1. 使用 Number(index) === 1;
2. 使用 index == 1。
建议使用第1种的显式类型转换,性能比第2种更优。