理解 JavaScript 中的物件迭代:'for...of”與'for...in”
迭代物件是 JavaScript 中常見的任務,但了解每種情況的正確技術可以使您的程式碼更乾淨、更有效率。本文解釋了為什麼不能直接將 for...of 與物件一起使用,提供了替代方法,並提供了迭代物件的最佳實踐。
目錄
- JavaScript 中的迭代簡介
- 為什麼 for...of 不適用於物件
- 迭代物件的技術
- 用於...
- 使用Object.keys()
- 使用 Object.values()
- 使用 Object.entries()
- 物件迭代技術的比較
- for...in 與 for...of 的比較
- 進階範例:迭代巢狀物件
- JavaScript 中物件迭代的最佳實踐
1. JavaScript 迭代簡介
在 JavaScript 中,迭代資料結構是處理複雜資料集的重要組成部分。雖然數組和字串是可迭代對象,但普通對象(鍵值對)需要不同的迭代方法。當開發人員嘗試在物件上使用 for...of 時,他們經常會遇到問題。
2. 為什麼 for...of 不適用於對象
for...of 迴圈用於迭代可迭代物件,例如陣列、字串、Map 和 Set。然而,預設情況下,普通 JavaScript 物件不可迭代。
範例:嘗試使用物件 for...of
const user = { name: 'John', age: 30 }; for (const value of user) { console.log(value); } // TypeError: user is not iterable
嘗試在普通物件上使用 for...of 會引發 TypeError。發生這種情況是因為 JavaScript 中的物件沒有 [Symbol.iterator] 方法,而 for...of 迴圈需要該方法。
3. 物件迭代技術
要在 JavaScript 迭代對象,可以使用多種技術:
3.1 用於...in
for...in 迴圈迭代物件的可枚舉屬性。它循環遍歷物件的鍵。
const user = { name: 'John', age: 30 }; for (const key in user) { console.log(key, user[key]); } // Output: // name John // age 30
- 優點:簡單直接。
- 缺點:如果繼承的屬性是可枚舉的,則會對其進行迭代,這可能會導致意外的行為。
3.2 使用Object.keys()
Object.keys() 傳回物件自身屬性鍵的數組,讓您可以使用 for...of 來迭代它們。
const user = { name: 'John', age: 30 }; for (const key of Object.keys(user)) { console.log(key, user[key]); } // Output: // name John // age 30
- 優點:僅迭代物件自己的屬性。
- 缺點:僅檢索鍵,而不檢索值。
3.3 使用Object.values()
Object.values() 傳回物件屬性值的數組,然後可以使用 for...of 進行迭代。
const user = { name: 'John', age: 30 }; for (const value of Object.values(user)) { console.log(value); } // Output: // John // 30
- 優點:無需處理鍵即可直接存取值。
- 缺點:無法直接存取金鑰。
3.4 使用Object.entries()
Object.entries() 傳回物件的鍵值對數組,這使得它非常適合迭代鍵和值。
const user = { name: 'John', age: 30 }; for (const [key, value] of Object.entries(user)) { console.log(key, value); } // Output: // name John // age 30
- 優點:在一次迭代中輕鬆存取鍵和值。
- 缺點:語法稍微複雜一些。
4. 物件迭代技術的比較
Technique | Access to Keys | Access to Values | Inherited Properties | Simplicity |
---|---|---|---|---|
for...in | Yes | Yes | Yes (if enumerable) | Simple |
Object.keys() for...of | Yes | No | No | Moderate |
Object.values() for...of | No | Yes | No | Moderate |
Object.entries() for...of | Yes | Yes | No | Slightly complex |
5. Comparison Between for...in and for...of
5.1 for...in Loop
The for...in loop is used to iterate over the enumerable properties (keys) of an object, including properties that may be inherited through the prototype chain.
Example: for...in with an Object
const user = { name: 'John', age: 30 }; for (const key in user) { console.log(key, user[key]); } // Output: // name John // age 30
- Explanation: The for...in loop iterates over the keys (name and age) and allows you to access the corresponding values (John and 30).
Example: for...in with an Array (Not Recommended)
const colors = ['red', 'green', 'blue']; for (const index in colors) { console.log(index, colors[index]); } // Output: // 0 red // 1 green // 2 blue
- Explanation: The for...in loop iterates over the indices (0, 1, 2) of the array, not the values themselves. This behavior is usually less desirable when working with arrays.
5.2 for...of Loop
The for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, and other iterables. It loops over the values of the iterable.
Example: for...of with an Array
const colors = ['red', 'green', 'blue']; for (const color of colors) { console.log(color); } // Output: // red // green // blue
- Explanation: The for...of loop directly iterates over the values of the array (red, green, blue), which is ideal for array iteration.
Example: for...of with a String
const name = 'John'; for (const char of name) { console.log(char); } // Output: // J // o // h // n
- Explanation: The for...of loop iterates over each character of the string (J, o, h, n), making it useful for string manipulation.
Summary: Key Differences Between for...in and for...of
Feature | for...in | for...of |
---|---|---|
Purpose | Iterates over object keys (including inherited properties) | Iterates over iterable values (arrays, strings, etc.) |
Works with Objects | Yes | No (objects are not iterable) |
Works with Arrays | Yes, but not ideal (returns indices) | Yes, ideal (returns values) |
Use Case | Best for iterating over object properties | Best for arrays, strings, maps, sets, etc. |
6. Advanced Example: Iterating Over Nested Objects
Sometimes, objects are nested, and you need to iterate through all levels of the object. Here's an example that uses recursion to handle nested objects.
const user = { name: 'John', age: 30, address: { city: 'New York', zip: 10001 } }; // Recursively iterate through the object function iterate(obj) { for (const [key, value] of Object.entries(obj)) { if (typeof value === 'object' && !Array.isArray(value)) { console.log(`Entering nested object: ${key}`); iterate(value); // Recursively call for nested objects } else { console.log(key, value); // Output key-value pair } } } iterate(user); // Output: // name John // age 30 // Entering nested object: address // city New York // zip 10001
- Explanation: The function checks if the value is an object, then recursively iterates through it.
7. Best Practices for Object Iteration in JavaScript
Use the Right Technique for the Right Task
- Use for...in cautiously: It may iterate over properties inherited from the prototype chain,
以上是理解 JavaScript 中的物件迭代:'for...of”與'for...in”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務
