JavaScript 中 for...of 与 for...in 循环的区别
发布: (2025年12月5日 GMT+8 06:59)
2 min read
原文: Dev.to
Source: Dev.to
在使用 JavaScript 时,了解 for...of 和 for...in 循环之间的区别对于编写简洁、高效的代码至关重要。虽然它们看起来相似,但用途不同,适用于不同的数据结构。
数组
for...of返回实际的元素。for...in返回索引(字符串形式)。
const data = ['apple', 'banana', 'cherry'];
// for...of – iterates over values
for (let item of data) {
console.log(item);
}
// Output:
// apple
// banana
// cherry
// for...in – iterates over keys (indices)
for (let index in data) {
console.log(index);
}
// Output:
// 0
// 1
// 2
字符串
for...of逐字符遍历。for...in遍历字符的索引(字符串形式)。
const text = "hello";
// for...of – characters
for (let char of text) {
console.log(char);
}
// Output: h e l l o
// for...in – indices
for (let index in text) {
console.log(index);
}
// Output: 0 1 2 3 4
对象
for...of不能直接用于普通对象(会抛出错误)。for...in遍历对象的可枚举属性键。
const person = { name: 'John', age: 30, city: 'NYC' };
// for...in – keys and values
for (let key in person) {
console.log(key, person[key]);
}
// Output:
// name John
// age 30
// city NYC