forEach方法的实现

 1 var arr = [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5];
 2 Array.prototype.forEach = Array.prototype.forEach || function(callback, thisArg) {
 3         if (!callback || typeof callback !== 'function') return;
 4         for (var i = 0, j = this.length; i < j; i++) {
 5             callback.call(thisArg, this[i], i, this);
 6         }
 7 }
 8 
 9 /*
10    forEach方法实现数组去重 
11 */
12 
13 var newArr = [];
14 arr.forEach(function(ele,index,arr){
15     if(arr.indexOf(ele)===index){
16         newArr.push(ele);
17     }
18 })
19 console.log(newArr);

 

posted @ 2017-04-09 14:17  惠远建  阅读(713)  评论(0编辑  收藏  举报