首页 > 代码库 > js中forEach,for in,for of的区别

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不能

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