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  更新时间

posted on   滔Roy  阅读(1783)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 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 自定义组件/控件图标

导航

点击右上角即可分享
微信分享提示