forEach

原生

var arr = [
  {
    name: 'Lance',
    age: 20,
  },
  {
    name: 'GC',
    age: 23
  },
  {
    name: 'Shank',
    age: 25
  }
];

var obj = {
  name: 'Lance',
  age: 23
}

arr.forEach(function(value, index, arr) {
  console.log(this); // 默认window
  console.log(value, index, arr);
}, obj);

Untitled

实现

Array.prototype.myForEach = function(cb) {
	var _arr = this,
      _len = _arr.length,
      _caller = arguments[1] || window;

  for (var i = 0; i < _len; i++) {
  	cb.call(_caller, _arr[i], i, _arr);
  }
}

map

原生

var arr = [
  {
    name: 'Lance',
    age: 20,
  },
  {
    name: 'GC',
    age: 23
  },
  {
    name: 'Shank',
    age: 25
  }
];

var obj = {
  name: 'Lance',
  age: 23
}

var newArr = arr.map(function(item, index, arr) {
  item.name = this.name;
  return item; // 必须返回,否则数组里边成员都是 undefined
}, obj);
console.log(newArr, arr);

Untitled

实现

Array.prototype.myMap = function(cb) {
	var _arr = this,
      _len = _arr.length,
      _caller = arguments[1] || window,
      newArr = [];

  for (var i = 0; i < _len; i++) {
    // var item = deepClone(_arr[i]); // 如果要实现深拷贝,可以加此行代码,同时把下边 _arr[i] 替换为 item
  	newArr.push(cb.call(_caller, _arr[i], i, _arr));
  }

  return newArr;
}

filter