一、对象遍历
// 循环一组对象 for in
let obj = {
name:'caixia',
age:11,
happy:'happy...'
}
for(let key in obj){
console.log(`每项的key为---${key },key值为---${obj[key ]}`)
}
输出:
每项的key为---name,key值为---caixia
每项的key为---age,key值为---11
每项的key为---happy,key值为---happy...
二、数组 for in跟 for of的区别
let arr = [
{
name: 'Mokeke',
age: 10,
},
{
name: 'caixia',
age: 10,
},
{
name: 'zijian',
age: 11,
},
]
// 数组for in 与for of的区别
for(let i in arr){
console.log(`for in 输出i为每一项的下标---${i}`)
}
for(let i of arr){
console.log(`for of 输出i为数组里边的每一项---${i}`,i)
}
for in 输出i为---0
test4.html:83 for in 输出i为---1
test4.html:83 for in 输出i为---2
for of 输出i为---[object Object] {name: "Mokeke", age: 10}
test4.html:87 for of 输出i为---[object Object] {name: "caixia", age: 10}
test4.html:87 for of 输出i为---[object Object] {name: "zijian", age: 11}
数组 for in 输出的是下标,
for of 输出的是元素
for in 相当于 《====》 for(let i =0; i < arr.length; i++){ }
三、更改数组中某一个键的值
一、 for(let i =0; i < arr.length; i++){ if(arr[i].age === 11){ arr[i].name = '莫小莫' }else{ arr[i].name = '小北' } } 二、 for(let i in arr){ if(arr[i].age === 11){ arr[i].name = '莫小莫' }else{ arr[i].name="小北" } } 三、 for (let i in arr) { if (arr[i].age === 11) { arr[i].name = '莫小莫' continue } arr[i].name = "小北" } console.log(arr, 'arr')