Javascript:遍历数组的forEach方法

介绍

  • forEach() 方法调用数组的每个元素,并将元素传递给回调函数。
  • 主要使用场景:遍历数组的每个元素
  • 语法形式:
要被遍历的数组.forEach(function (当前数组元素, 当前元素索引号) {
  // 处理逻辑
})
  • forEach() 方法只遍历数组,不返回值。如果打印返回值的话,是undefined。
  • 参数当前数组元素是必须要写的,索引号可选。

示例

打印数组的当前元素、及元素索引号

<!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 = ['red', 'green', 'blue']
    arr.forEach(function (item, index) {
      console.log(item, index)
    })
  </script>
</body>

</html>

在这里插入图片描述

forEach() 方法返回值是undefined

<!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 = ['red', 'green', 'blue']
    const result = arr.forEach(function (item, index) {
      console.log(item, index)
    })
    console.log(result)
  </script>
</body>

</html>

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值