JavaScript forEach()的用法

在这里插入图片描述
forEach 是 ES5 中操作数组的一种方法,主要功能是遍历数组,其实说穿了,就是 for 循环的加强版,该语句需要一个回调函数,作为参数。回调函数的形参,依次为,value:遍历的数组内容;index:对应的数组索引,array:数组本身。

<script type="text/javascript">
	// 分别对应:数组元素,元素的索引,数组本身
	var arr = ['a','b','c'];	
	arr.forEach(function(value,index,array){
		console.log(value);
		console.log(index);
		console.log(array);
		})
</script>

在这里插入图片描述
for 循环比较步骤多比较复杂,forEach 循环比较简单好用,不容易出错。

发布了161 篇原创文章 · 获赞 71 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_44034384/article/details/99290078