JS之for...in for...of以及可枚举,可迭代

一、for...in for...of区别

  1. for...in遍历得到key, for...of遍历得到value
  2. for...in遍历可枚举的数据类型, for...of遍历可迭代的数据类型

二、可枚举 vs 可迭代

  1. 可枚举数据,如对象、数组、字符串
  2. 可迭代数据,如数组、字符串、Map、Set
  3. 举例
    let obj = { name:'lisi', age:23, gender:'男'} //可枚举
    let arr = [1, 2, 3] //可枚举 可迭代
    // 判断对象的属性是否可迭代iterable
    console.log(typeof obj[Symbol.iterator] === 'function')
    console.log(typeof arr[Symbol.iterator] === 'function')
    // 判断对象的属性是否可枚举enumerable
    console.log(obj.propertyIsEnumerable('name'))
    // 检查对象可枚举属性enumerable是否为true
    console.log(Object.getOwnPropertyDescriptors(arr))
    //obj不可迭代
    for(let item of obj){
        console.log(key)
    }

猜你喜欢

转载自blog.csdn.net/qq_45199056/article/details/126386521
今日推荐