写在前面:
在对数组或对象进行遍历时,我们经常会使用到两种方法: for in和for of,那么这两种方法之间的区别,我们今天直接使用例子来说明
被遍历的数组:
orderDocotorList[
{"DoctorId":"1","DoctorName":"测试","DoctorCode":"3","DoctorSkill":null,"DoctorDesc":null,"DoctorTitle":null,"DoctorSex":null,"LocationId":"1","LocationName":"内二科","LocationCode":"001","LocationRoom":"测试诊室","LocationRoomId":null},
{"DoctorId":"42","DoctorName":"孙继良","DoctorCode":"10042","DoctorSkill":null,"DoctorDesc":null,"DoctorTitle":null,"DoctorSex":null,"LocationId":"1","LocationName":"内二科","LocationCode":"001","LocationRoom":"心血管内科","LocationRoomId":null},
{"DoctorId":"42","DoctorName":"孙继良","DoctorCode":"10042","DoctorSkill":null,"DoctorDesc":null,"DoctorTitle":null,"DoctorSex":null,"LocationId":"1","LocationName":"内二科","LocationCode":"001","LocationRoom":"心血管内科","LocationRoomId":null}
]
两种遍历方法:
for in
for (const doctorItem of this.orderDocotorList){
console.log('遍历数组',doctorItem,doctorItem.DoctorId)
}
输出结果:
for of
for (const index in this.orderDocotorList){
console.log('遍历数组',index,index.DoctorId)
}
输出结果:
结论:
for in遍历的是数组的索引(即键名),而for of遍历的是数组元素值
for in总是得到对象的key或数组、字符串的下标
for of总是得到对象的value或数组、字符串的值