• js中forEach,for in,for of的区别


    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    <script>
        var arr = [1,2,3];
        arr.four = 4;
        console.log(arr);
    
        arr.forEach(value => {
            /*if(value > 2) {
                break
        }*/
            console.log(value)//1,2,3
        })
    
        for(let i in arr) {
            console.log(i); // '0' '1' '2' 'four' 相当于对象的key值
            console.log(arr[i]) // 1,2,3,4 相当于对象的value值
        }
    
        for (let i of arr) {
            if(i > 2) {
                break
            }
            console.log(i); // 1,2,3  数值中的每一项的值
            console.log(arr[i]);//2,3,undefined 相当于arr[1],arr[2],arr[3]
        }
    
        for (let i of 'my') {
            console.log(i); // 'm' 'y'
        }
    
        for (let i of arr) {
            if(i > 2) {
                break
            }
            console.log(i); // 1,2 
        }
    
    </script>
    </body>
    </html>

    总结:如果遍历数组最好用for of,遍历对象用for in
    for of遍历数组和forEach遍历数组的区别:for of能用break语句,forEach不能

  • 相关阅读:
    CSP2018-09
    CSP2018-03
    CSP2017-12
    CSP2017-09
    CSP2017-03
    CSP2016-12
    [算法设计与分析] 奶酪 (并查集)
    5555
    阿超
    结对作业
  • 原文地址:https://www.cnblogs.com/yesyes/p/6789749.html
Copyright © 2020-2023  润新知