总结的一些js手写题,多写写可以巩固js语法知识
深拷贝
function deepCopy(obj){
let res
if(typeof obj === 'object'){
res = obj.constructor === Array ? [] : {}
for(let k in obj){
res = typeof obj[k] === 'object' ? deepCopy(obj[k]) : obj
}
}else{
res = obj
}
return res
}
数组扁平化的多种写法
function flatten(arr){
let res = []
arr.forEach(item => {
if(Array.isArray(item)){
res = res.concat(flatten(item))
}else{
res.push(item)
}
})
return res
}
function flatten(arr){
return arr.reduce((pre,item) => {
return pre.concat(Array.isArray(item) ? flatten(item) : item)
},[])
}
手写reduce
Array.prototype.myReduce = function(fn,init){
if(typeof fn !== 'function'){
throw new TypeError('error')
}
let initialArr = this
let arr = initialArr.concat()
let index,newValue
if(arguments.length === 2){
arr.unshift(init)
index = 0
}else{
index = 1
}
if(arr.length === 1){
return newValue
}
while(arr.length > 1){
newValue = fn.call(null,arr[0],arr[1],index,initialArr)
index++
arr.splice(0,2,newValue)
}
return newValue
}
手写map
Array.prototype.myMap = function(fn){
let newArr = []
for(let i = 0; i < this.length; i++){
newArr.push(fn(this[i],i,this))
}
return newArr
}
手写fill
Array.prototype.myFill = function(value,start = 0, end = this.length){
for(let i = start; i < end; i++){
this[i] = value
}
}
手写filter
Array.prototype.myFilter = function(fn,context){
let temp = []
for(let i = 0; i < this.length; i++){
let res = fn.call(context,this[i],i)
if(res) temp.push(this[i])
}
return temp
}
手写find
Array.prototype.myFind(fn){
for(let i = 0; i < this.length; i++){{
let res = fn.call(this,this[i],i,this)
if(res) return this[i]
}
}
手写findIndex
Array.prototype.myFindIndex = function(fn){
for(let i = 0; i < this.length; i++){{
let res = fn.call(this,this[i],i,this)
if(res) return i
}
return -1
}
手写ajax请求
var xhr = new XMLHttpRequest()
var url = 'https://sdf.com'
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log(xhr.responseText)
}else{
console.error(xhr.statusText)
}
}
}
xhr.open('GET',url,true)
xhr.send(null)
模拟实现instanceof
function instanceofObj(a,b){
let prototypeB = b.prototype
let protoA = a.__proto__
let state = false
while(true){
if(protoA === null){
state = false
break
}
if(prototypeB === protoA){
state = true
break
}
protoA = protoA.__proto__
}
return state
}
console.log(instanceofObj([],Array))
用setTimeout实现setInterval
function mysetInterval(fn,time){
function interval(){
setTimeout(interval,time)
fn()
}
setTimeout(interval,time)
}
mysetInterval(function(){
console.log(0)
},1000)
字符串逆序
func