• [JavaScript]_[初级]_[关于forof或者for...of循环语句的用法]


    场景

    1. 在开发网页时,经常需要枚举NodeList类型的数据,比如通过document.body.childNodes获取的, 通过DOM.querySelectorAll也能获取到NodeList对象。那么这个返回的对象除了for...i方式枚举,还有更快的方法吗?

    说明

    1. 枚举NodeList对象,最快的方法就是使用for...of循环语句。 它可以直接枚举出值,不需要再通过索引访问。variable每次迭代都会得到迭代对象的下一个值。variable可以用var,let,const修饰。
    for (variable of iterable) {
        //statements
    }
    
    • 1
    • 2
    • 3
    1. 枚举可迭代对象,包括Array,Map,Set,String,TypeArray,arguments对象等。它是的原理是创建一个迭代循环,调用自定义的钩子(yield xx), 返回不同的值。

    2. for...of不能枚举普通的key,value对象类型. {a:"a",b:"b"}.

    3. 迭代完成后,或者通过在循环体里调用break,throw,return,生成器会(function*实例)关闭,因此不要重用生成器。

    4. 只迭代可迭代对象迭代值, 其他属性值不会迭代。

    例子

    <html>
        <head>
            <style>
                .read{
                    color: blue;
                }
                .bold{
                    font-weight: 600;
                }
            style>
        head>
        <body>
            <p id="out">for...ofp>
        body>
        <script>
            function print(str){
                let p = document.createElement("p");
                p.innerHTML = str;
                document.body.append(p)
            }
    
            function printSingleIteratorValue(data){
                for(const p of data)
                    print(p);
            }
    
            function printSinglePropertyValue(data){
                for(const p in data)
                    print(`${p}=${data[p]}`);
            }
    
            print("1. 迭代 Map.");
            let visitData = new Map([["a", 1], ["b", 2], ["c", 3]]);
            for(const p of visitData){
                print(`${p[0]} = ${p[1]}`);
                p[1] = 100; //p是临时变量, 不会影响原来的值。
            }    
            print("-- [key,value] 形式");
            for(const [key,value] of visitData)
                print(`${key} = ${value}`);    
            
            print("2. Array, TypeArray, Set 和 String");
            let visitArray = [10, 20, 30];
            let visitTypeArray = new Uint8Array([0x00, 0xff]);
            let visitSet = new Set([1, 1, 2, 2, 3, 3]);
            let visitString = "Tobey";
    
            print("-- Array");
            printSingleIteratorValue(visitArray);
    
            print("-- TypeArray");
            printSingleIteratorValue(visitTypeArray);
    
            print("-- Set");
            printSingleIteratorValue(visitSet);
    
            print("-- String");
            printSingleIteratorValue(visitString);
    
    
            print("3. 函数参数arguments对象");
            (function(){
                printSingleIteratorValue(arguments);
            })(1,2,3,4);
    
    
            print("4. 只枚举可迭代对象的数组迭代值, 非迭代值的属性objCustom,arrCustom,foo不迭代")
            Object.prototype.objCustom = function() {};
            Array.prototype.arrCustom = function() {};
    
            let iterable = [3, 5, 7];
            iterable.foo = 'hello';
            printSingleIteratorValue(iterable);
    
            print("-- for...in");
            printSinglePropertyValue(iterable);
    
            print("5. 迭代自定义生成器,break关闭生成器之后不可用!");
            var gen = (function *(){
                yield 1;
                yield 2;
                yield 3;
            })();
    
            for (let o of gen) {
                print(o);
                break;//关闭生成器
            }
    
            
            print("-- 生成器不应该重用,以下不会输出。");
            for (let o of gen) 
                print(o);
            
    
            print("6. 迭代DOM集合, NoteList对象");
            let ps = document.querySelectorAll("p");
            print("-- 增加字体蓝色样式");
            for(let one of ps)
                one.classList.add("read")
            
            print("-- 增加粗体样式");
            for(let i = 0; i<ps.length; i++)
                ps[i].classList.add("bold");
            
    
        script>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108

    输出

    for...of
    
    1. 迭代 Map.
    
    a = 1
    
    b = 2
    
    c = 3
    
    -- [key,value] 形式
    
    a = 1
    
    b = 2
    
    c = 3
    
    2. Array, TypeArray, Set 和 String
    
    -- Array
    
    10
    
    20
    
    30
    
    -- TypeArray
    
    0
    
    255
    
    -- Set
    
    1
    
    2
    
    3
    
    -- String
    
    T
    
    o
    
    b
    
    e
    
    y
    
    3. 函数参数arguments对象
    
    1
    
    2
    
    3
    
    4
    
    4. 只枚举可迭代对象的数组迭代值, 非迭代值的属性objCustom,arrCustom,foo不迭代
    
    3
    
    5
    
    7
    
    -- for...in
    
    0=3
    
    1=5
    
    2=7
    
    foo=hello
    
    arrCustom=function() {}
    
    objCustom=function() {}
    
    5. 迭代自定义生成器,break关闭生成器之后不可用!
    
    1
    
    -- 生成器不应该重用,以下不会输出。
    
    6. 迭代DOM集合, NoteList对象
    
    -- 增加字体蓝色样式
    
    -- 增加粗体样式
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97

    参考

    1. for…of - JavaScript | MDN

    2. HTML DOM 元素对象

    3. HTML DOM querySelectorAll() 方法

  • 相关阅读:
    java计算机毕业设计水质监测数据采集系统源码+系统+数据库+lw文档+mybatis+运行部署
    集合—Vector底层结构和源码分析
    SQL server从安装到入门(一)
    【JAVA进阶篇】时间与日期相关类
    Python Flask Web开发二:数据库创建和使用
    Activiti,Apache camel,Netflex conductor对比,业务选型
    基于文本IO实现的小程序
    lambda 表达式
    K8S基础架构租赁(Lease )
    ES6 不完全手册(上)
  • 原文地址:https://blog.csdn.net/infoworld/article/details/126687568