forEach for-in for-of在Object Array Set Map中异同点

forEach

  1. 可以遍历数组和类数组对象
  2. 可以遍历Set和Map
  3. Set遍历出的item和index相同
  4. 不能遍历Object
  5. break,continue,return无效
  6. 从下标0遍历到length-1
  7. 不会遍历数组上自定义的自有属性和自定义的原型属性(0<n<length-1的数组除外)

for-in

  1. 可以遍历数组和对象
  2. 遍历出来的是键
  3. 不能遍历Set和Map,会遍历所有自定义的自有属性和自定义的原型属性
  4. 键会自动转成字符串类型
  5. break,continue,return有效

for-of

  1. 可以遍历数组和类数组对象
  2. 可以遍历Set和Map结构
  3. 遍历出来的是值
  4. 不能遍历对象
  5. 可以避免所有 for-in 循环的陷阱
  6. 支持字符串的遍历
  7. break,continue,return有效

定义测试变量

let obj={
  a:1,
  b:2,
  c:3
}
obj.__proto__.d=4;

let arr=[3,4,5];
arr.name=22;
arr.__proto__.d=66;

let s=new Set();
s.add(1);
s.add("2");
s.add({b:3});

let m=new Map();
m.set({a:4},3);
m.set(3,4);
m.set("4",5);

测试对象

console.log("forEach========");
obj.forEach((item,idx)=>{
  console.log(item,idx);
});
console.log("for-in========");
for(let index in obj){
  console.log(index,obj[index]);
}
console.log("for-of========");
for(let item of obj){
  console.log(item,s[item]);
}

//结果
forEach========
//报错
for-in========
a 1
b 2
c 3
d 4
for-of========
//报错

测试数组

console.log("forEach========");
arr.forEach((item,idx)=>{
  console.log(item,idx);
});
console.log("for-in========");
for(let index in arr){
  console.log(index,arr[index]);
}
console.log("for-of========");
for(let item of arr){
  console.log(item,arr[item]);
}

//结果
forEach========
3 0
4 1
5 2
for-in========
0 3
1 4
2 5
name 22
d 66
for-of========
3 undefined
4 undefined
5 undefined

测试Set

console.log("forEach========");
s.forEach((item,idx)=>{
  console.log(item,idx);
});
console.log("for-in========");
for(let index in s){
  console.log(index,s[index]);
}
console.log("for-of========");
for(let item of s){
  console.log(item,s[item]);
}

//结果
forEach========
1 1
2 2
{ b: 3 } { b: 3 }
for-in========
d 4
for-of========
1 undefined
2 undefined
{ b: 3 } undefined

测试Map

console.log("forEach========");
m.forEach((item,idx)=>{
  console.log(item,idx);
});
console.log("for-in========");
for(let index in m){
  console.log(index,m[index]);
}
console.log("for-of========");
for(let item of m){
  console.log(item,m[item]);
}

//结果
forEach========
3 { a: 4 }
4 3
5 '4'
for-in========
d 4
for-of========
[ { a: 4 }, 3 ] undefined
[ 3, 4 ] undefined
[ '4', 5 ] undefined
发布了38 篇原创文章 · 获赞 66 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/lyt_angularjs/article/details/84571234