functionmyNew(fn,...args){let obj ={}
obj.__proto__ = fn.prototype
let res =fn.apply(obj,args)// 这里的instanceof如何理解?// 其实就是看res是不是undefined或者null,如果是就返回新对象,不是就返回数值return res instanceofObject? res : obj
}
// forEachArray.prototype.myForEach=function(fn){if(typeof fn !='function'){thrownewTypeError('not a function!')}// 这里的self其实就是数组var self =this// afor(let i =0; i < self.length; i++){// 回调函数可以传三个参数,分别是当前元素,当前元素下标,整个数组fn(self[i],i,self)}}var a =[1,2,3,4]
a.myForEach(num=>{console.log(num);})// mapArray.prototype.myMap=function(fn){if(typeof fn !='function'){thrownewTypeError('not a function')}let self =thislet res =[]for(let i =0; i < self.length; i++){
res[i]=fn(self[i],i,self)}return res
}var a =[1,2,3,4]var ans = a.myMap(num=> num*2)
console.log(ans);// filterArray.prototype.myFilter=function(fn){if(typeof fn !='function'){thrownewTypeError('not a function')}let self =thislet res =[]for(let i =0; i < self.length; i++){fn(self[i],i,self)&& res.push(self[i])}return res
}var a =[1,2,3,4]var ans = a.myFilter(num=> num >3)
console.log(ans);// findArray.prototype.myFind=function(fn){if(typeof fn !='function'){thrownewTypeError('not a function')}let self =thisfor(let i =0; i < self.length; i++){if(fn(self[i],i,self)){return self[i]}}}var a =[1,2,3,4]var ans = a.myFind(num=> num >=3)
console.log(ans);// everyArray.prototype.myEvery=function(fn){if(typeof fn !='function'){thrownewTypeError('not a function')}let self =thisfor(let i =0; i < self.length; i++){if(!fn(self[i],i,self)){returnfalse}}returntrue}var a =[1,2,3,4]var ans = a.myEvery(num=> num >=3)
console.log(ans);// someArray.prototype.mySome=function(fn){if(typeof fn !='function'){thrownewTypeError('not a function')}let self =thisfor(let i =0; i < self.length; i++){if(fn(self[i],i,self)){returntrue}}returnfalse}var a =[1,2,3,4]var ans = a.mySome(num=> num >=3)
console.log(ans);
手写xhr发送请求
functionAjax(url){const p =newPromise((resolve, reject)=>{const xhr =newXMLHttpRequest()
xhr.open('GET', url)
xhr.onreadystatechange=function(){if(xhr.readyState ===4){if(xhr.status ===200){resolve(JSON.parse(xhr.responseText))}}elseif(xhr.status ===404){reject(newError('404 Not Found'))}}
xhr.send(null)})return p
}