Js的for In、for of及froEach的区别

  1. 先总结:
  2. for…in
  3. for of
    1. for of与for in的不同

先总结:

  • for in 适用于纯对象的遍历,并且只能输出可枚举属性
  • forEach适用于需要知道索引值的数组遍历,但是不能中断
  • for of适用于无需知道索引值的数组遍历,因为可以中断。另外对于其他字符串,类数组,类型数组的迭代,for of也更适用

for…in

for in是为遍历对象属性而构建的,它以任意顺序遍历一个对象的除Symbol以外的可枚举属性,可用break或者throw跳出。

  • 语法
    for (variablename in object) {
      // 可枚举属性
      // 注意: 不是可枚举属性
      console.log(variablename);
    }
    
  • 例子:
    1. 遍历对象
    let obj = {
      name: 'xiaoming',
      age: 18
    }
    for(let item in obj){
      console.log(item)
    }
    // 输出:name age
    
    1. 遍历数组:返回数组的索引值
    let arr = ['a', 'b', 'c'];
     for(let item in arr){
       console.log(item)
     }
     // 输出: 0 1 2
    
    1. 需要注意的是,for in会遍历原型链的属性
    Array.prototype.ufo = 'xiaoqiang';
    let arr = ['a', 'b', 'c'];
    for(let item in arr){
     console.log(item)
    }
    // 输出:0 1 2 ufo
    

for of

for of语句在可迭代对象上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句(包括ArrayMapSetStringTypedArrayArgument等,不包括Object)可用break或者throw跳出。

  • 语法
for(variable of 可迭代对象){
  // 操作语句
}
  • 例子
    let arr = ['a', 'b', 'c']
    
    let obj = {
      name: '张三',
      age: 18,
      sex: '男'
    }
    
    for (let i of arr) {
      console.log(i)
    }
    // 输出 a b c
    
    for (let i of obj) {
      console.log(i)
    }
    // 报错 obj is not iterable (obj不是可迭代的)
    

for of与for in的不同

  • for...of不像for...in, 它不支持遍历普通对象,因为普通对象没有迭代器接口。但是可以通过Object.key()去遍历迭代。

  • for...of支持 迭代 Unicode 字符串、setmap

  • for...of可以通过await关键字每次迭代中等待异步任务

for await ( value in statcks ) {
    //...
}
  • 语法:
for (variable in object) {
  // 在此执行代码
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 chaoyumail@126.com

×

喜欢就点赞,疼爱就打赏