語法
array.forEach(function(currentValue, index, arr), thisValue)
參數
參數 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | 必需。 數組中每個元素需要調用的函數。 函數參數:
|
||||||||
thisValue | 可選。傳遞給函數的值一般用 "this" 值。 如果這個參數為空, "undefined" 會傳遞給 "this" 值 |
實例
計算數組所有元素相加的總和:
<buttononclick="numbers.forEach(myFunction)">點我</button><p>數組元素總和:<spanid="demo"></span></p><script> var sum = 0; var numbers = [65, 44, 12, 4]; function myFunction(item) { sum += item; demo.innerHTML = sum; } </script>
來源: http://www.runoob.com/jsref/jsref-foreach.html
實例
將數組中的所有值乘以特定數字:
<p>乘以: <inputtype="number"id="multiplyWith"value="10"></p><buttononclick="numbers.forEach(myFunction)">點我</button><p>計算后的值: <spanid="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> 來源: http://www.runoob.com/jsref/jsref-foreach.html
值得注意的是 數組執行forEach之后,會改變了原數組的值,並且第三個參數即代表數組
forEach 只有在IE9以上才可以使用,為了更好的使用這個方法,有專門做了一個IE8的兼容
if ( !Array.prototype.forEach ) { Array.prototype.forEach = function forEach( callback, thisArg ) { var T, k; if ( this == null ) { throw new TypeError( "this is null or not defined" ); } var O = Object(this); var len = O.length >>> 0; if ( typeof callback !== "function" ) { throw new TypeError( callback + " is not a function" ); } if ( arguments.length > 1 ) { T = thisArg; } k = 0; while( k < len ) { var kValue; if ( k in O ) { kValue = O[ k ]; callback.call( T, kValue, k, O ); } k++; } }; }