ES6中的JSON數組(JSON Array)使用起來非常方便,這篇文章將向大家介紹如何對JSON數組進行常見的操作。
// 創建JSON數組 let students = [ {name:'張三', age:18}, {name:'李四', age:20}, {name:'王五', age:22} ]; // 獲取JSON數組中的某一項 let firstStudent = students[0]; console.log(firstStudent); // 輸出:{name:'張三', age:18} // 遍歷JSON數組 students.forEach((student) =>{ console.log(student.name); }); // 過濾JSON數組 let over20Students = students.filter((student) =>{ return student.age >20; }); console.log(over20Students); // 輸出:[{name:'王五', age:22}] // 映射JSON數組 let studentNames = students.map((student) =>{ return student.name; }); console.log(studentNames); // 輸出:['張三', '李四', '王五'] // 向JSON數組中添加新元素 students.push({name:'趙六', age:25}); console.log(students); // 輸出:[{name:'張三', age:18}, {name:'李四', age:20}, {name:'王五', age:22}, {name:'趙六', age:25}]
通過以上示例,我們可以發現,ES6中的JSON數組非常靈活,具有豐富的功能,對于處理數據非常有幫助。