JS forEach()第二个参数

4,844 阅读1分钟

定义和用法

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

注意: forEach() 对于空数组是不会执行回调函数的。

语法

array.forEach(function(currentValue, index, arr), thisValue)

实例

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			[1, 2, 3, 4, 5].forEach(function(a) {
				console.log(a, this)
			})
		</script>
		<script type="text/javascript">
			[1, 2, 3, 4, 5].forEach(function(a) {
				console.log(a, this)
			}, [6, 7, 8, 9])
		</script>
		<script type="text/javascript">
			Array.prototype.forEach.call([1, 2, 3, 4, 5], function(a) {
				console.log(a, this)
			}, [6, 7, 8, 9])
		</script>
		<script type="text/javascript">
			Array.prototype.forEach.apply([1, 2, 3, 4, 5], [function(a) {
					console.log(a, this)
				},
				[6, 7, 8, 9]
			])
		</script>
		<script type="text/javascript">
			Array.prototype.forEach.bind([1, 2, 3, 4, 5])(function(a) {
				console.log(a, this)
			}, [6, 7, 8, 9])
		</script>
	</head>

	<body>
	</body>

</html>