zoukankan      html  css  js  c++  java
  • for...of 与 for...in 区别

    一、for...of

    1.定义

    for...of 语句遍历可迭代对象(包括数组、Set 和 Map 结构、arguments 对象、DOM NodeList 对象、字符串等)。

    2.语法

    for (variable of iterable) {
        //statements
    }
    

    3.示例

    <ul>
        <li>mazey</li>
        <li>luna</li>
        <li>cherrie</li>
    </ul>
    <script>
    // 数组
    let arr = ['mazey', 'luna', 'cherrie'];
    for (let v of arr) {
        console.log(v);
    }
    // mazey luna cherrie
    
    // 字符串
    let str = 'mlc';
    for (let v of str) {
        console.log(v);
    }
    // m l c
    
    // 类数组对象
    let obj = {
        0: 'mazey',
        1: 'luna',
        2: 'cherrie',
        length: 3
    };
    // 需使用Array.from转换成可迭代对象
    for (let v of Array.from(obj)) {
        console.log(v);
    }
    // mazey luna cherrie
    
    // Set
    let s = new Set(['mazey', 'luna', 'cherrie']);
    for (let v of s) {
        console.log(v);
    }
    // mazey luna cherrie
    
    // Map
    let m = new Map([
        ['name0', 'mazey'],
        ['name1', 'luna'],
        ['name2', 'cherrie']
    ]);
    for (let [i, v] of m) {
        console.log(v);
    }
    // mazey luna cherrie
    
    // DOM NodeList
    let domList = document.querySelectorAll('li');
    for (let v of domList) {
        console.log(v.innerText);
    }
    // mazey luna cherrie
    </script>
    

    二、for...of 与 for...in 区别

    1.for...in 遍历键名,for...of 遍历键值

    let arr = ['mazey', 'luna', 'cherrie'];
    for (let k in arr) {
        console.log(k);
    }
    // 0 1 2
    for (let v of arr) {
        console.log(v);
    }
    // mazey luna cherrie
    

    2.for...in 会把对象上手动添加的属性和原型上的属性暴露出来

    let obj = {
        0: 'mazey',
        1: 'luna',
        2: 'cherrie',
        length: 3
    };
    obj.name = 'objName';
    for (let k in obj) {
        console.log(k);
    }
    // 0 1 2 length name
    for (let v of Array.from(obj)) {
        console.log(v);
    }
    // mazey luna cherrie
    

    三、for...of 其它优点

    1.相对于数组自带的 forEach 方法,for...of 可以与 break、continue 和 return 配合使用。
    2.正确识别32位 UTF-16 字符。

    for…of 与 for…in 区别

  • 相关阅读:
    TCP/IP——何时用UDP代替TCP
    网络编程——客户/服务器程序设计范式
    各种常见英特网应用协议的使用情况和传输层三大协议的异同
    linux dd使用记录
    杂谈-为什么我们不要去外包公司
    小雪的成都
    哪个的情感
    mac上的git completion
    ue4 UE4Editor.lib找不到
    ue4 重新生成ide project文件的命令行
  • 原文地址:https://www.cnblogs.com/mazey/p/8629158.html
Copyright © 2011-2022 走看看