for of 和 for in 的区别

1.遍历对象

for ... of

        var obj = {
            a: 1,
            b: [],
            c: function () {}
            };
            for (var key of obj) {
            console.log(key);
            //出错
            //Uncaught TypeError: obj is not iterable
            }

for ... in

        var obj = {
            a: 1,
            b: [],
            c: function () {}
            };
            for (var key in obj) {
            console.log(key);
            //打印
            // a 
            // b
            // c
            }

2.遍历数组

for ... of(打印的是值)

        var arr=[1,2,3]
        for(let i of arr){
            console.log(i)
        }
        //结果是
        //1
        //2
        //3

for ... in(打印的是坐标)

        var arr=[1,2,3]
        for(let i in arr){
            console.log(i)
        }
        //结果是
        //0
        //1
        //2

3.遍历map

for ... of

        let map = new Map([["a", 1], ["b", 2], ["c", 3]]);
        for(let entry of map){
            console.log(entry)
        }
        //输出:
        //["a", 1]
        //["b", 2]
        //["c", 3]

for ... in

        let map = new Map([["a", 1], ["b", 2], ["c", 3]]);
        for(let entry in map){
            console.log(entry)
        }
        //啥都不输出

4.遍历set

for ... of

        let set = new Set([1, 1, 2, 2, 3, 3]);
        for(let i of set){
            console.log(i);
        }
        //1
        //2
        //3

for ... in

        let set = new Set([1, 1, 2, 2, 3, 3]);
        for(let i in set){
            console.log(i);
        }
        //啥都不输出

5.总结

  1. for-of 无法遍历 不可迭代对象

可迭代对象包括: Array,Map,Set,String,TypedArray,arguments等等

  1. for-of 遍历的是值,for-in遍历的是key

 

posted @ 2021-07-21 16:37  本兮嘻嘻  阅读(66)  评论(0编辑  收藏  举报