循環存取 JavaScript 普通物件的物件成員
使用 JavaScript 物件時,通常需要遍歷其成員。但是,當物件包含子物件時,循環遍歷它們需要專門的方法。
基於鍵值對的循環
循環遍歷普通 JavaScript 對象,你可以使用:
for (var key in object) { // Loop through the object's key-value pairs }
範例:
var validation_messages = { "key_1": { "your_name": "jimmy", "your_message": "hello world" }, "key_2": { "your_name": "billy", "your_message": "foo equals bar" } }; for (var key in validation_messages) { // Output: "jimmy" and "billy" console.log(validation_messages[key].your_name); // Output: "hello world" and "foo equals bar" console.log(validation_messages[key].your_message); }
巢狀物件迭代
巢狀處理物件時,您可以使用巢狀循環:
for (var key in object) { if (!object.hasOwnProperty(key)) continue; // Skip prototype properties var subObject = object[key]; for (var subKey in subObject) { // Loop through the sub-object's key-value pairs } }
範例:
for (var key in validation_messages) { // If property exists in this object if (!validation_messages.hasOwnProperty(key)) continue; var subObject = validation_messages[key]; for (var subKey in subObject) { // If property exists in this sub-object if (!subObject.hasOwnProperty(subKey)) continue; // Output: "jimmy" and "billy" console.log(validation_messages[key].your_name); // Output: "hello world" and "foo equals bar" console.log(validation_messages[key].your_message); } }
此方法可確保您迭代所有鍵值對,即使對於巢狀物件也是如此。
以上是如何在 JavaScript 中迭代嵌套物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!