Array.prototype.myForEach = function(func) {
var len = this.length;
for(var i = 0; i < len; i++) {
func(this[i], i);
}
}
複製代碼
Array.prototype.myFilter = function(func) {
var len = this.length,
newArr = [];
for(var i = 0; i < len; i++) {
if(func(this[i], i)) {
newArr.push(this[i]);
}
}
return newArr;
}
複製代碼
Array.prototype.myMap = function(func) {
var len = this.length,
newArr = [];
for(var i = 0; i < len; i++) {
newArr.push(func(this[i], i));
}
return newArr;
}
複製代碼
// 深度克隆
function deepClone(target, option) {
if(option !== null) {
for(var prop in option) {
var src = target[prop],
copy = option[prop];
if(typeof(copy) === 'object') {
if(Object.prototype.toString(copy) === '[object Array]') {
src = [];
}else {
src = {};
}
target[prop] = deepClone(src, copy);
}else {
target[prop] = copy;
}
}
}
return target;
}
Array.prototype.myMap = function(func) {
var len = this.length,
newArr = [];
for(var i = 0; i < len; i++) {
if(this[i] && Object.prototype.toString.call(this[i]) === '[object Object]') {
var newObj = {};
deepClone(newObj, this[i]);
newArr.push(func(newObj, i));
}else if(this[i] && Object.prototype.toString.call(this[i]) === '[object Array]') {
var Arr = [];
deepClone(newArr, this[i]);
newArr.push(func(Arr, i));
}else {
newArr.push(func(this[i], i));
}
}
return newArr;
}
複製代碼
做用: 迭代數組,從左向右,累加器(效率高)。數組
源碼實現學習
Array.prototype.myMap = function(func, init) {
var k = 0,
prev = init,
len = this.length;
if(init === undefined) {
prev = this[0];
k = 1;
}
for(k; k < len; k++) {
prev = func(prev, this[k], k);
}
return prev;
};
複製代碼
Array.prototype.myReduceRight = function(func, init) {
var prev = init,
len = this.length,
k = len - 1;
if(init === undefined) {
prev = this[k];
k = len - 2;
}
for(k; k >= 0; k --) {
prev = func(prev, this[k], k);
}
return prev;
}
複製代碼