• 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

    一点点学习,一丝丝进步。不懈怠,才不会被时代所淘汰!

  • 相关阅读:
    POJ 3904 Sky Code (容斥原理)
    HDU 4334 Trouble (暴力)
    UVA 10325 The Lottery( 容斥原理)
    HDU 2841 Visible Trees 数论+容斥原理
    UVA11806-Cheerleaders(容斥原理+二进制)
    HDU1695 GCD (欧拉函数+容斥原理)
    HDU 5651 xiaoxin juju needs help (组合数)
    最大子矩阵和 51Nod 1051 模板题
    最大子段和 模板题 51Nod 1049
    51Nod 1006 最长公共子序列Lcs问题 模板题
  • 原文地址:https://www.cnblogs.com/fqh2020/p/15040167.html
Copyright © 2020-2023  润新知