循环访问 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中文网其他相关文章!