let li=document.getElementsByTagName("li")
for(var i=0;i<5;i++){
li[i].onclick=function (j){
console.log(j)
}(i)
}
for(var k =0;k<5;k++){
(function(j){
setTimeout(function(){
console.log(j)
},j*1000)
})(k)
}
Array.prototype.myFilter = function (fn, context) {
let result = []
const me = this
const ctx = context ? context : this
if (typeof fn != "function") {
throw new Error(`${fn} is not function`)
}
me.forEach((item, index) => {
console.log("ctx", ctx.fn)
const bool = fn.call(ctx, item, index, me)
if (bool) {
result.push(item)
}
})
return result
}
Array.prototype.myMap = function (fn, context) {
let resArr = []
const me = this
const ctx = context ? context : this
if (typeof fn != "function") {
throw new Error(`${fn} is not function`)
}
me.forEach((item, index) => {
resArr.push(fn.call(ctx, item, index, me))
})
return resArr
}
Array.prototype.myReduce = function (fn, initialValue) {
let that = this
if (typeof fn !== "function") {
throw new Error(`${fn} is not function`)
}
let prev, currentValue, currentIndex
if (initialValue) {
prev = initialValue
currentIndex = 0
} else {
prev = arr[0]
currentIndex = 1
}
while (currentIndex < that.length) {
let currentValue = that[currentIndex]
prev = fn(prev, currentValue, currentIndex, that)
currentIndex++
}
return prev
}
Function.prototype.myCall = function (context) {
if (typeof context != "function") {
throw new Error("不是一个函数")
}
context = context ? context : window
context.fn = this
const args = [...arguments].slice(1)
const result = context.fn(...args)
delete context.fn
return result
}
Function.prototype.myApply = function (context) {
if (typeof context != "function") {
throw new Error("不是一个函数")
}
context = context ? context : window
context.fn = this
let result = null
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
// 返回一个函数
return function F() {
// 因为返回了一个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
return new _this(...args, ...arguments)
}
console.log("args.concat(...arguments)==",args, ...arguments)
let a=args.concat(...arguments)
console.log("a=",a)
return _this.apply(context, a)
}
}
常见面试题
最新推荐文章于 2023-02-25 08:07:24 发布