一、定義和用法
forEach( )方法用于調用數組的每個元素,并将元素傳遞給回調函數。
二、注意
forEach( )方法對空數組是不會執行回調函數的。
三、文法
array.forEach(function(currentValue,index,arr),this.Value)
四、參數
參數 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | 必需。 數組中每個元素需要調用的函數。 函數參數:
| ||||||||
thisValue | 可選。傳遞給函數的值一般用 "this" 值。 如果這個參數為空, "undefined" 會傳遞給 "this" 值 |
五、demo
1.列出數組的每個元素:
<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
2.計算數組所有元素相加的總和:
<button onclick="numbers.forEach(myFunction)">點我</button>
<p>數組元素總和:<span id="demo"></span></p>
<script>
var sum = 0;
var numbers = [65, 44, 12, 4];
function myFunction(item) {
sum += item;
demo.innerHTML = sum;
}
</script>
輸出結構:
125
3.将數組中的所有值乘以特定數字:
<p>乘以: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="numbers.forEach(myFunction)">點我</button>
<p>計算後的值: <span id="demo"></span></p>
<script>
var numbers = [65, 44, 12, 4];
function myFunction(item,index,arr) {
arr[index] = item * document.getElementById("multiplyWith").value;
demo.innerHTML = numbers;
}
</script>
輸出結果:
650, 440, 120, 40