typescript-中-for..of-和-for..in的区别
目录
typescript 中 for..of 和 for..in的区别
[
JavaScript性能优化实战
10w+人浏览
331人参与
](
)
for..of - 遍历值
用于遍历可迭代对象的值(数组元素、字符串字符、Map/Set 的值等)。
// 数组
const arr = [10, 20, 30];
for (const value of arr) {
console.log(value); // 10, 20, 30
}
// 字符串
const str = "hello";
for (const char of str) {
console.log(char); // 'h', 'e', 'l', 'l', 'o'
}
// Map
const map = new Map([['a', 1], ['b', 2]]);
for (const [key, value] of map) {
console.log(key, value); // 'a' 1, 'b' 2
}
for..in - 遍历键/属性名
用于遍历对象的可枚举属性名(包括原型链上的属性)。
// 对象
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key); // 'a', 'b', 'c'
console.log(obj[key]); // 1, 2, 3
}
// 数组(不推荐)
const arr = [10, 20, 30];
for (const index in arr) {
console.log(index); // '0', '1', '2' (字符串)
console.log(arr[index]); // 10, 20, 30
}
主要区别
特性 | for..of | for..in |
---|---|---|
遍历内容 | 值 | 键/属性名 |
适用对象 | 可迭代对象 | 任何对象 |
原型链属性 | 不遍历 | 会遍历 |
数组索引类型 | 不适用 | 字符串 |
性能 | 通常更好 | 稍慢 |
实际使用建议
// 数组 - 使用 for..of
const numbers = [1, 2, 3];
for (const num of numbers) {
console.log(num); // 1, 2, 3
}
// 对象 - 使用 for..in(配合 hasOwnProperty)
const person = { name: "John", age: 30 };
for (const key in person) {
if (person.hasOwnProperty(key)) {
console.log(`${key}: ${person[key]}`);
}
}
// 更好的对象遍历方式
Object.keys(person).forEach(key => {
console.log(`${key}: ${person[key]}`);
});
// 或者使用 Object.entries
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
重要注意事项
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
Person.prototype.gender = 'male'; // 在原型上添加属性
const john = new Person('John', 25);
// for..in 会遍历原型链上的属性
for (const key in john) {
console.log(key); // 'name', 'age', 'gender'
}
// for..of 不能直接用于普通对象
// 这会报错:TypeError: john is not iterable
// for (const value of john) { }
总结:使用 for..of
遍历数组和可迭代对象的值,使用 for..in
(谨慎地)遍历对象的属性名。