for...in 与for ...of的区别

for ..in 用来遍历迭代对象的键

          即  如果 for. ..in 遍历的是数组,则输出的值 数组的下标

         例子 

    this.str = new Array();
    this.str.push('15');
    this.str.push('20');
    this.str.push('29');
    for (const i in  this.str) {
        console.log(i);     i为数组的下标值
    }
  如果 for...in 遍历的是对象,则输出的值 是对象个 键(key)
 
const personInfo = {
      name: '张三', age: 29, addr: '我在这里,等风,也等你'
    };
 
 
    for (const ss in personInfo) {
       console.log(ss);  ss的值为 name 、age、addr
     }
 
for...of 用来遍历迭代数组的值
  this.str = new Array();
    this.str.push('15');
    this.str.push('20');
    this.str.push('29');
    for (const i of   this.str) {
        console.log(i);    i的值为‘15’,‘20’,‘29’
    }

猜你喜欢

转载自www.cnblogs.com/kukai/p/12228862.html