forEach 以及 IE兼容

 

语法

array.forEach(function(currentValue, index, arr), thisValue)

参数

参数描述
function(currentValue, index, arr) 必需。 数组中每个元素需要调用的函数。
函数参数:
参数描述
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++;
        }
    };
}

  

 



posted @ 2017-07-19 18:42  佳明兄  阅读(9311)  评论(0编辑  收藏  举报

内容仅为参考使用,不保证内容的正确性,通过使用本博客内容随之而来的风险与作者无关。内容如有侵权,请通知删除!