介绍
- 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>