首先定义一个数组对象
let student = [ {id:1,name:'小明',number:1001,test:60}, {id:2,name:'小红',number:1002,test:70}, {id:3,name:'小黄',number:1003,test:55}, {id:4,name:'小蓝',number:1004,test:90}, {id:5,name:'小紫',number:1005,test:59}, {id:6,name:'小粉',number:1006,test:61} ]
for…of
//遍历数组对象 for (let item of student) { console.log('name', item.name) console.log('test', item.test) }
可用于判断某个学号为xxxx的学生的成绩?
//提取学号为1002的学生的成绩 let test for (let item of student) { if (item.number == 1002) { test = item.test } } console.log('1002学生的成绩为',test)
filter函数
//过滤及格的人 let passStudent = student.filter(el => el.test >= 60) console.log('passStudent', passStudent)
filter用法二
let student = [ {id:1,name:'小明',number:1001,test:60}, {id:2,name:'小红',number:1002,test:70}, {id:3,name:'小黄',number:1003,test:55}, {id:4,name:'小蓝',number:1004,test:90}, {id:5,name:'小紫',number:1005,test:59}, {id:6,name:'小粉',number:1006,test:61} ] let patient = [ {id:2021001,name:'小明',illnessId:'10000000000'}, {id:2021002,name:'小黄',illnessId:'10000000001'}, {id:2021003,name:'小绿',illnessId:'10000000002'}, {id:2021004,name:'小新',illnessId:'10000000003'}, {id:2021005,name:'小思',illnessId:'10000000004'} ] //查找两个数组对象的交集 let intersection = student.filter(bp => { if (patient.findIndex(lp => lp.name == bp.name) != -1) return { ...bp } }) console.log('intersection', intersection)
其中findIndex()函数用法
回调函数有三个参数。value:当前的数组元素。index:当前索引值。arr:被查找的数组。
当条件为true时findIndex()返回索引值,如果没有符合条件元素时findIndex()返回的是-1
.map() 通过指定函数调用一个数组中每一项元素,来创建一个新数组
1.返回对象中的部分数据:例如返回id和name列
let passstudentin = [] passstudentin = student.map(bp => { return { id: bp.id, name: bp.name } }) console.log('passstudentidname', passstudentin)
2. 对象数组去重
let student = [ {id:1,name:'小明',number:1001,test:60}, {id:2,name:'小红',number:1002,test:70}, {id:3,name:'小黄',number:1003,test:55}, {id:4,name:'小蓝',number:1004,test:90}, {id:5,name:'小紫',number:1005,test:59}, {id:6,name:'小粉',number:1006,test:61}, {id:6,name:'小粉',number:1006,test:61}, ] //去重 let map = new Map() student.forEach((item,index)=>{ if (!map.has(item['id'])){ map.set(item['id'],item) } }) console.log([...map.values()])
3. 给符合条件的对象添加元素
//当某学生生病时,在student对象中添加illness:true let whoillness = student.map(bp => { if (patient.findIndex(lp => lp.name == bp.name) != -1) return { ...bp, illness: true } return bp }) console.log('whoillness', whoillness)