美文网首页
forEach() 方法

forEach() 方法

作者: 遥远不是北_ | 来源:发表于2018-09-28 11:01 被阅读6次

定义和用法

  • forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
  • 注意: forEach() 对于空数组是不会执行回调函数的。
<button onclick="numbers.forEach(myFunction)">点我</button>
<p id="demo"></p>
 
<script>
demoP = document.getElementById("demo");
var numbers = [4, 9, 16, 25];
 
function myFunction(item, index) {
    demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>"; 
}
</script>

输出结果:

index[0]: 4
index[1]: 9
index[2]: 16
index[3]: 25

相关文章

网友评论

      本文标题:forEach() 方法

      本文链接:https://www.haomeiwen.com/subject/jiiuoftx.html