for in 和 for of 的区别

1.for in 和 for of 都可以循环数组,for in 输出的是数组的 index 下标,而 for of 输出的是数组的每一项的值。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const arr = [1, 2, 3, 4, 5]

        // for in
        for (const index in arr) {
            console.log(index); // 输出 0, 1, 2, 3, 4
        }

        // for of
        for (const item of arr) {
            console.log(item) // 输出 1, 2, 3, 4, 5
        }
    </script>
</body>

</html>

2.for in 可以遍历对象,for of 不能遍历对象,只能遍历带有iterator(迭代器)接口的,例如Set,Map,String,Array。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const object = { name: 'Jack', age: 18 }

        // for ... in
        for (const key in object) {
            console.log(key) // 输出 name,age
            console.log(object[key]) // 输出 Jack,18
        }

        // for ... of
        for (const key of object) {
            console.log(key) // 报错 Uncaught TypeError: object is not iterable
        }
    </script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 使用for...of循环遍历Set实例的例子
        const mySet = new Set([1, 2, 3, 4, 5]);

        // 使用for...of循环遍历Set中的元素
        for (const value of mySet) {
            console.log(value); // 打印每个元素的值
        }

        // 使用for...of循环遍历Map对象的例子
        const map = new Map();

        // 添加键值对
        map.set('key1', 'value1');
        map.set('key2', 'value2');
        map.set('key3', 'value3');

        // 使用for...of遍历Map对象
        for (const [key, value] of map) {
            console.log(key + ' = ' + value);
        }
    </script>
</body>

</html>

3.数组对象

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const list = [{ name: 'Jack' }, { age: 18 }]
        for (const val of list) {
            console.log(val) // 输出 { name: 'Jack' },{ age: 18 }
            for (const key in val) {
                console.log(val[key]) // 输出 Jack,18
            }
        }
    </script>
</body>

</html>

总结:for in 适合遍历对象,for of 适合遍历数组。for in 遍历的是数组的索引,对象的属性,以及原型链上的属性。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值