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

87 阅读1分钟

for...in

循环主要是为了遍历对象而生,不适用于遍历数组

  • 例子 ---正常版本
const objs = {a: 1, b: 2, c: 3};
for(let item in objs) {
  console.log(item);
}

/**
打印如下
  a
  b
  c
*/
  • 例子 --- 添加原型在遍历
const objs = {a: 1, b: 2};
Object.prototype.nihao = 666;
for(let item in objs) {
  console.log(item);
}

/**
  打印结果:a,b,nihao
*/

// for in 可以遍历到objs的原型属性nihao,如果不想遍历原型方法和属性的话
// 可以在循环内部判断一下, hasOwnPropery 方法可以判断某属性是否是该对象的实例属性

for(let item in objs) {
  if (objs.hasOwnPropery(item)) {
    console.log(item);
  }
}

/**
  打印结果:a,b
*/


for...of

适用遍历数/数组对象/字符串/map/set等拥有迭代器对象的集合.但是不能遍历对象,因为没有迭代器对象.与forEach()不同的是,它可以正确响应break、continue和return语句

  • 例子 --- 正常
// 数组的
const arrs = ['a','b','c']
for(let index of arrs) {
    console.log(index)
}
/**
  打印结果:a,b,c
*/

// 字符串的
const str = 'yydream';
for(let s of str) {
    console.log(s)
}
/**
  打印结果:y,y,d,r,e,a,m
*/