ES5中提供了許多方法來遍歷JSON對象,使得我們可以方便地從其中獲取所需的數(shù)據(jù)。以下是幾種常見的ES5 JSON遍歷方法。
// 1. for in循環(huán)遍歷JSON對象 var data = { name: "張三", age: 18, gender: "男" }; for (var key in data) { console.log(key + ": " + data[key]); } // 2. forEach遍歷JSON數(shù)組 var arr = [ { name: "張三", age: 18, gender: "男" }, { name: "李四", age: 25, gender: "男" }, { name: "王五", age: 30, gender: "女" } ]; arr.forEach(function(item) { console.log(item.name + ": " + item.age + "歲," + item.gender); }); // 3. filter過濾JSON數(shù)組 var arr2 = [ { name: "張三", age: 18, gender: "男" }, { name: "李四", age: 25, gender: "男" }, { name: "王五", age: 30, gender: "女" } ]; var result = arr2.filter(function(item) { return item.gender === "男"; }); console.log(result); // 4. map遍歷JSON數(shù)組并返回新的數(shù)組 var arr3 = [ { name: "張三", age: 18, gender: "男" }, { name: "李四", age: 25, gender: "男" }, { name: "王五", age: 30, gender: "女" } ]; var result2 = arr3.map(function(item) { return item.name; }); console.log(result2);
以上是ES5中常用的JSON遍歷方法,通過這些方法可以快速地獲取所需的數(shù)據(jù)。在實際開發(fā)過程中,我們可以根據(jù)具體需求選擇使用適當?shù)谋闅v方法,提高代碼效率。