ES5的 forEach, map 方法的实现

如果浏览器不支持forEach,map方法, 要我们自己封装一个, 该怎么操作呢?

1. forEach

1 Array.prototype.forEach = function(fn) {
2   if (this.length === 0) {
3     return;
4   }    
5   for (var i=0;i<this.length;i++) {
6     fn(this[i], i, this)  
7   }  
8 }

2. map要复杂一点, 因为map最后会返回一个新数组

 1 Array.prototype.map = function(fn, context) {
 2   if (this.length === 0) {
 3     return;  
 4   }
 5   var arr = [];
 6   for (var i=0;i<this.length;i++) {
 7       arr.push(fn.call(context, this[i], i, this))
 8   }
 9   return arr;
10 }

forEach, map迭代都会执行一个fn, 所以在forEach,map中return是不能终止循环的, 要在中途中断循环还是乖乖的用for循环吧

原文地址:https://www.cnblogs.com/spotman/p/10375990.html