Array.prototype.myMap = function (fn, context) {
let resArr = []
let _this = this
let ctx = context ? context : _this
if (Object.prototype.toString.call(fn) !== "[object Function]") {
throw new Error(`${fx}is not a function!`);
}
_this.forEach((item, index) => {
let l = fn.call(ctx, item, index, _this)
console.log('l', l)
console.log('_this', _this)
console.log('ctx', ctx)
resArr.push(l)
})
console.log('resArr', resArr)
return resArr
}
Array.prototype.myReduce = function (fn, initVal) {
if (Object.prototype.toString.call(fn) !== '[object Function]') {
throw new Error(`${fn} is not a funciton`)
}
let resVal = initVal || this[0]
let startIndex = initVal ? 0 : 1
for (var i = startIndex, len = this.length; i < len ; i++) {
resVal = fn(resVal, this[i], i, this)
}
return resVal
}
Array.prototype.myFilter = function (callbackFn, thisArg) {
if (Object.prototype.toString.call(callbackFn) !== "[object Function]") {
throw new Error(`${callbackFn} is not function`)
}
var res = []
for (var i = 0, len = this.length; i < len; i ++) {
var exit = callbackFn.call(thisArg, this[i], i, this)
console.log('thisArg', thisArg)
console.log('exit', exit)
exit && res.push(this[i])
}
return res
}
const arr = [1, 2, 3, 4];
arr.myFilter((item) => item > 2);
arr.myFilter("555");
function copyObj(obj){
var cloneObj;
if(obj&&typeof obj!=='object'){cloneObj=obj;}
else if(obj&&typeof obj==='object'){
cloneObj=Array.isArray(obj)?[]:{};
for(let key in obj){
if(obj.hasOwnProperty(key)){
if(obj[key]&&typeof obj[key]==='object') {
cloneObj[key] = copyObj(obj[key]);
}
else{cloneObj[key]=obj[key];}
}
}
}
return cloneObj;
}
Function.prototype.myTestApply = function () {
if ( typeof this !== 'function') {
throw new Error('error')
}
let [context, args] = [...arguments]
context = context ? context : window
context.fn = this
let res = context.fn(...args)
delete context.fn
return res
}
Function.prototype.myBind = function (context, arg1) {
context = context ? context : window
let _this = this
return function (arg2) {
context.fn = _this
let res = context.fn(...[...arg1,...arg2])
delete context.fn
return res
}
}
function throttle (fn, t) {
var timer = null
return function () {
let _this = this
let arg = arguments
if (!timer) {
timer = setTimeout(() => {
fn.apply(_this, arg)
timer = null
}, t)
}
}
}
function debounce (fn, t) {
let _this = this
let timer = null
return function () {
let arg = arguments
if (timer) {
clearInterval(timer)
}
timer = setTimeout(() => {
fn.apply(_this, arg)
}, t)
}
}