定义和用法
- 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
网友评论