typescript 中 for..of 和 for..in的區(qū)別
for..of - 遍歷值
用于遍歷可迭代對(duì)象的值(數(shù)組元素、字符串字符、Map/Set 的值等)。
// 數(shù)組
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 - 遍歷鍵/屬性名
用于遍歷對(duì)象的可枚舉屬性名(包括原型鏈上的屬性)。
// 對(duì)象
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
}
// 數(shù)組(不推薦)
const arr = [10, 20, 30];
for (const index in arr) {
console.log(index); // '0', '1', '2' (字符串)
console.log(arr[index]); // 10, 20, 30
}主要區(qū)別
| 特性 | for..of | for..in |
|---|---|---|
| 遍歷內(nèi)容 | 值 | 鍵/屬性名 |
| 適用對(duì)象 | 可迭代對(duì)象 | 任何對(duì)象 |
| 原型鏈屬性 | 不遍歷 | 會(huì)遍歷 |
| 數(shù)組索引類型 | 不適用 | 字符串 |
| 性能 | 通常更好 | 稍慢 |
實(shí)際使用建議
// 數(shù)組 - 使用 for..of
const numbers = [1, 2, 3];
for (const num of numbers) {
console.log(num); // 1, 2, 3
}
// 對(duì)象 - 使用 for..in(配合 hasOwnProperty)
const person = { name: "John", age: 30 };
for (const key in person) {
if (person.hasOwnProperty(key)) {
console.log(`${key}: ${person[key]}`);
}
}
// 更好的對(duì)象遍歷方式
Object.keys(person).forEach(key => {
console.log(`${key}: ${person[key]}`);
});
// 或者使用 Object.entries
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}重要注意事項(xiàng)
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 會(huì)遍歷原型鏈上的屬性
for (const key in john) {
console.log(key); // 'name', 'age', 'gender'
}
// for..of 不能直接用于普通對(duì)象
// 這會(huì)報(bào)錯(cuò):TypeError: john is not iterable
// for (const value of john) { }總結(jié):使用 for..of 遍歷數(shù)組和可迭代對(duì)象的值,使用 for..in(謹(jǐn)慎地)遍歷對(duì)象的屬性名。
到此這篇關(guān)于typescript 中 for..of 和 for..in的區(qū)別的文章就介紹到這了,更多相關(guān)typescript for..of 和 for..in內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端實(shí)現(xiàn)加密的常見(jiàn)方法和步驟
這篇文章主要介紹了前端實(shí)現(xiàn)加密的常見(jiàn)方法和步驟,包括對(duì)稱(AES)、非對(duì)稱(RSA/ECC)及哈希(SHA-256)算法,推薦使用WebCryptoAPI、CryptoJS等工具,需要的朋友可以參考下2025-06-06
uniapp開(kāi)發(fā)H5使用formData上傳文件解決方案
我們很多時(shí)候上傳文件就是使用FormData,然而uniapp默認(rèn)不支持FormData類型數(shù)據(jù)的上傳,下面這篇文章主要給大家介紹了關(guān)于uniapp開(kāi)發(fā)H5使用formData上傳文件的相關(guān)資料,需要的朋友可以參考下2023-12-12
WordPress中鼠標(biāo)懸停顯示和隱藏評(píng)論及引用按鈕的實(shí)現(xiàn)
這篇文章主要介紹了WordPress中鼠標(biāo)懸停顯示和隱藏評(píng)論及引用按鈕的實(shí)現(xiàn),順帶顯示和隱藏評(píng)論者信息的實(shí)現(xiàn)方法,非常實(shí)用,需要的朋友可以參考下2016-01-01
vue3 uniapp微信登錄功能實(shí)現(xiàn)
根據(jù)最新的微信小程序官方的規(guī)定,uniapp中的uni.getUserInfo方法不再返回用戶頭像和昵稱、以及手機(jī)號(hào),這篇文章主要介紹了vue3 uniapp微信登錄功能實(shí)現(xiàn),需要的朋友可以參考下2024-04-04
javascript入門之?dāng)?shù)組[新手必看]
本文介紹了javascript 數(shù)組的定義和數(shù)組元素的操作,ECMAScript中的數(shù)組方法...希望對(duì)大家有所幫助2016-11-11

