低版本IE數組和HTMLCollection元素集合不兼容forEach循環遍歷的處理方法

原生JavaScript通過name獲取dom元素得到的是
HTMLCollection元素集合
要想循環遍歷可以用forEach,但是在低於ie9的版本下不兼容

var list= document.getElementsByName("name");
for (var i = 0; i < list.length; i++) {
    console.log(list[i].id); //second console output
}

數組的時候可以向Array.prototype加一個自定義方法forEach
如下:

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++;
        }
    };
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章