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 对象
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 对象数组
// 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 对象
// 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 对象数组
// 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 希望内容对你有所帮助,谢谢!