JavaScript 之 JSON [3] 的所有循环输出方式(for循环、while循环、forEach()函数、map()函数、filter()函数和Object.keys()函数)
JavaScript 之 JSON [3] 的所有循环输出方式(for循环、while循环、forEach()函数、map()函数、filter()函数和Object.keys()函数)
1、for循环、while循环、forEach()函数
1.1 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | var JSONObject,Jvale; JSONObject= { //对象 "name" : "滔Roy" , "date" : "2023.04.14" , "other" :[12, "TaoRoy" , null , true ] //数组 }; // for循环遍历JSON对象属性 for ( let key in JSONObject) { console.log(key + ": " + JSONObject[key]); } // while循环遍历JSON对象属性 let keys = Object.keys(JSONObject); let i = 0; while (i < keys.length) { console.log(keys[i] + ": " + JSONObject[keys[i]]); i++; } // forEach()函数遍历JSON对象属性 Object.keys(JSONObject).forEach((key) => { console.log(key + ": " + JSONObject[key]); }); |
1.2 对象数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // for循环遍历JSON数组 for ( let i = 0; i < JSONObject.other.length; i++) { console.log(JSONObject.other[i]); } // while循环遍历JSON数组 let j = 0; while (j < JSONObject.other.length) { console.log(JSONObject.other[j]); j++; } // forEach()函数遍历JSON数组 JSONObject.other.forEach((item) => { console.log(item); }); |
结果:
2、map()函数、filter()函数
2.1 对象
1 2 3 4 5 6 7 8 9 10 11 | // map()函数遍历JSON对象属性并返回新数组 const mapArray = Object.keys(JSONObject).map((key) => { return key + ": " + JSONObject[key]; }); console.log(mapArray); //["name: TaoRoy","date: 2023.04.14","other: 12,TaoRoy,2023,true"] // filter()函数遍历JSON数组并返回符合条件的元素组成的新数组 const filterArray = JSONObject.other.filter((item) => { return typeof item === "string" ; }); console.log(filterArray); //["TaoRoy"] |
2.2 对象数组
1 2 3 4 5 6 7 8 9 10 11 | // map()函数遍历JSON数组并返回新数组 const mapArray2 = JSONObject.other.map((item) => { return item + " is " + typeof item; }); console.log(mapArray2); //["12 is number","TaoRoy is string","2023 is number","true is boolean"] // filter()函数遍历JSON数组并返回符合条件的元素组成的新数组 const filterArray2 = JSONObject.other.filter((item) => { return typeof item === "number" ; }); console.log(filterArray2); //[12,2023] |
注意:在使用map()函数和filter()函数时,需要将其应用于JSON对象的属性值所组成的数组。
创建时间:2023.04.14 更新时间:
博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你有所帮助,谢谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
2022-04-14 Delphi Clipboard[6] SetAsHandle、GetAsHandle 自定义格式,以指定格式处理数据
2022-04-14 Delphi Clipboard[5] SetComponent、GetComponent -组件在剪贴板中的操作
2022-04-14 Delphi Clipboard[4] Formats、FormatCount -格式化列表
2022-04-14 Delphi Clipboard[3] HasFormat、Assign及Image图片的加载
2022-04-14 Delphi Clipboard[2] SetTextBuf、GetTextBuf、AsText -文本操作
2022-04-14 Delphi Clipboard[1] 剪贴板 介绍
2021-04-14 Delphi 自定义组件/控件图标