方便好找
for of
遍历数组中的每一项(1)数组里面是字符串
const arr = ["apple", "banana", "purple"];
for(const item of arr) {
console.log(item)
}
// 控制台结果:
apple
banana
purple
(2) 数组里面是对象
const arr = [
{ name: "milk", price: 3 },
{ name:"water", price: 2 },
{name: "juice",price: 7},
];
for ( const item of arr) {
console.log(item.name, item.price);
}
// 控制台结果:
milk 3
water 2
juice 7
for in
(1)遍历数组
···
const arr = [“apple”, “banana”, “purple”];
for (const index in arr) {
console.log(index + “—” + arr[index]);
}
//控制台结果:
0—apple
1—banana
2—purple
(2) 遍历对象
const userMsg = {
Tom: {
name: "Tom",
age: 20,
gender: "男",
},
Lisa: {
name: "Lisa",
age: 22,
gender: "女",
},
};
for (const key1 in userMsg) {
console.log(key1);//Tom Lisa
for (const key2 in userMsg[key1]) {
console.log(key2 + ":" + userMsg[key1][key2]);
}
}
//控制台结果:
name:Tom
age:20
gender:男
name:Lisa
age:22
gender:女``
for of 与for in 的区别
1.for of无法循环遍历对象
2.遍历输出结果不同:for in 循环遍历说 数组的索引,而 for of 循环遍历的是数组的值。
3.for in会遍历自定义属性,for of 不会
var arr = ['nick','freddy','mike','james'];
arr.name = "数组";
for(var key in arr){
console.log(key+': '+arr[key]);
}
console.log('-----------分割线-----------');
for(var item of arr){
console.log(item);
}
//控制台结果:
0: nick
1: freddy
2: mike
3: james
name: 数组
-----------分割线-----------
nick
freddy
mike
james
给数组添加一个自定义属性name,并且赋值"数组"。然后进行遍历输出的,会发现新定义的属性也被for in输出来了,而for of并不会对name进行输出