typescript 中 for..of 和 for..in的区别
作者:心随雨下
本文主要介绍了typescript 中 for..of 和 for..in的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
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
(谨慎地)遍历对象的属性名。
到此这篇关于typescript 中 for..of 和 for..in的区别的文章就介绍到这了,更多相关typescript for..of 和 for..in内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!