美文网首页
for in 和for of实用对比

for in 和for of实用对比

作者: 玖肆seven | 来源:发表于2021-01-12 10:30 被阅读0次

    for……in……是ES3的
    1, 遍历对象:

    const obj = {a:1, b:2 ,c:3}
    for (const i in obj) {
            i  // a b c
            obj[i] // 1 2 3
    }
    

    2, 遍历数组:

    const arr= ['a', 'b' ,'c']
    for (const i in arr) {
            i  // 0 1 2
            arr[i] // a b c
    }
    

    for……of……是ES6的
    先看遍历数组

    const arr = ['a', 'b', 'c']
    for (const i of arr) {
          i // a b c
    }
    

    着重看一下遍历对象
    还是先遍历个普通对象

    const obj = {a:1, b:2 ,c:3}
    for (const i of obj) {
            console.log(i)
    }
    

    啪!报错了


    image.png

    所以这个iterable是什么呢?
    这里就要说到for……of……是不能遍历普通对象的,只限于迭代器(iterator)。
    打印数组和对象就能看出对比:

    image.png
    那么,这些可以被遍历的统统成为可迭代对象(包括Array, Map, Set, String, TypedArray, arguments对象等等)
    那一个普通对象就不能使用for……of遍历了嘛?当然不是。
    1,如果是 类数组对象,直接用Array.from()转化为数组即可。
    const obj = {
        0: 1
        1: 2
        length: 2
    }
    obj  = Array.from(obj)
    for(const i of obj){
        console.log(i)
    }
    

    2, 如果是 非类数组对象

    const obj = {
        a:1,
        b:2,
        c:3
    };
     // function*(){},es6新语法,function 后面带 * 的叫做generator,
     // 当你调用一个generator函数的时候,你会获得一个iterator对象,
     // 在generator内部你可以使用 yield 语句
    obj[Symbol.iterator] = function*(){
        const keys = Object.keys(obj)
        for(const i of keys){
            yield [i,obj[i]]
        }
    };
    
    for(const [k,v] of obj){
        console.log(k,v)
    }
    

    3,遍历数组对象

    const list  = [{
    name:'我是谁',
    age:'几岁啦'
    }, {
    name:'我是皮卡丘',
    age:'5岁啦'
    }]
    for (const i of list) {
       i.name // 我是谁 我是皮卡丘
       i.age // 几岁啦 5岁啦
    }
    

    for……of……迭代普通对象最优解
    ES6中有 Object.keys() 、 Object.values() 、 Object.entries() 和for of 配合迭代。

    const obj = {
        a: 1,
        b: 2,
        c: 3
    };
    for(const key of Object.keys(obj)) { // Object.keys(obj)=>["a", "b","c"]
        console.log(key);
    }
    // 结果 :  a  b  c
    for(const value of Object.values(obj)) {// Object.values(obj)=>[1,2,3]
        console.log(value);
    }
    // 结果 :  1  2  3
    for(const [index , item] of Object.entries(obj)) { // Object.entries(obj)=>[["a",1],["b",2],["c",3]]
        // 这里用方括号,主要看你要解构的是什么格式
        console.log(index,item);
    }
    // 结果 a  1  b  2  c  3
    
    何以解忧 唯有学习

    相关文章

      网友评论

          本文标题:for in 和for of实用对比

          本文链接:https://www.haomeiwen.com/subject/nyaxaktx.html