今天聊聊forEach;
首先看看foreach的用法:
1. 原生JS的forEach:
參數:value數組中的當前項, index當前項的索引, array原始數組;
var?ary?=?[1,2,3,4];
ary.forEach(function?(value,index,array)?{
????console.log(value+"------"+index +"------------"+array);
})
輸出結果:
1------0------------1,2,3,4
2------1------------1,2,3,4
3------2------------1,2,3,4
4------3------------1,2,3,4
2. jQuery的$.each
參數:index當前項的索引;value數組中的當前項;array要遍歷的數組;
var?ary?=?[1,2,3,4];
$.each(ary,function(index, value, array) {
console.log(index+"------"+ value);
});
輸出結果:
0------1
1------2
2------3
3------4
如果瀏覽器不支持foreach方法,那么需要我們自己封裝一個都兼容的方法,代碼如下:
if( !Array.prototype.forEach) {
Array.prototype.forEach = function forEach(callback){
// 獲取數組長度
var len =this.length;
if( ?typeof callback != "function" ) {
throw new TypeError() ;
?}
// thisArg為callback 函數的執行上下文環境
var thisArg = arguments[1];
for(vari =0; i < len; i++) {
if ( i in this ) {
// callback函數接收三個參數:當前項的值、當前項的索引和數組本身
callback.call( thisArg , this[i] , i , this ) ;?
?}
?}
?}
}