JavaScript For In

For In 循环

JavaScript for in 语句循环遍历对象的属性:

语法

for (key in object) {
  // code block to be executed
}

实例

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

<body>
    <P id="demo"></P>
    <script>
        const person = { fname: "Rose", lname: "Jenny", age: 20 };
        let txt = "";
        for (let x in person) {
            txt += person[x] + "";
        }
        document.getElementById("demo").innerHTML = txt;
    </script>
</body>

</html>

//RoseJenny20

例子解释

  • for in 循环遍历 person 对象
  • 每次迭代返回一个 (x)
  • 键用于访问键的
  • 键的值为 person[x]

For In 遍历数组

JavaScript for in 语句也可以遍历数组的属性:

语法

for (variable in array) {
  code
}

实例

<!DOCTYPE html>
<html>

<body>

    <p id="demo"></p>

    <script>
        const numbers = [45, 4, 9, 16, 25];

        let txt = "";
        for (let x in numbers) {
            txt += numbers[x] + "<br>";
        }

        document.getElementById("demo").innerHTML = txt;
    </script>

</body>

</html>

果索引顺序很重要,请不要在数组上使用 for in

索引顺序依赖于实现,可能不会按照您期望的顺序访问数组值。

当顺序很重要时,最好使用 for 循环、for of 循环或 Array.forEach()

Array.forEach()

forEach() 方法为每个数组元素调用一次函数(回调函数)

<!DOCTYPE html>
<html>

<body>

    <p id="demo"></p>

    <script>
        const numbers = [45, 4, 9, 16, 25];

        let txt = "";
        numbers.forEach(myFunction);
        document.getElementById("demo").innerHTML = txt;

        function myFunction(value, index, array) {
            txt += value + "<br>";
        }
    </script>

</body>

</html>

请注意,该函数采用 3 个参数:

  • 项目值
  • 项目索引
  • 数组本身
<!DOCTYPE html>
<html>

<body>
    <p id="demo"></p>

    <script>
        const numbers = [45, 4, 9, 16, 25];

        let txt = "";
        numbers.forEach(myFunction);
        document.getElementById("demo").innerHTML = txt;

        function myFunction(value) {
            txt += value + "<br>";
        }
    </script>

</body>

</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值