常见的js试题

深拷贝

function deepCopy(obj) {
    //终止条件,也是表示基本类型直接赋值
    if (typeof obj != 'object';) {
        return obj
    }
    let copyObj = {}
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            //递归调用
            copyObj[key] = deepCopy(obj[key])
        }
    }
    return copyObj
}
console.log(deepCopy(tree));

快排

function quickSort(arr) {
    //终止条件
    if (arr.length <= 1) {
        return arr
    }
    let pivotIndex = Math.floor(arr.length / 2)
    let pivot = arr.splice(pivotIndex, 1)[0]
    let left = []
    let right = []
    for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        if (element < pivot) {
            left.push(element)
        } else {
            right.push(element)
        }
    }
    //循环递归调用
    return quickSort(left).concat([pivot], quickSort(right))
}
console.log(quickSort([2, 1, 5, 3, 4]));

防抖:在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。

function debounce(func, dealy) {
    let timer;
    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            //箭头函数取的是前一个不是箭头函数的arguments和this,所以可以直接绑定
            func.apply(this, arguments)
        }, dealy)
    }
}

节流:函数在某一时间段只执行一次

function throttle(func, delay) {
    let timer;
    return function () {
        if (timer) {
            return
        }
        timer = setTimeout(() => {
            //箭头函数取的是前一个不是箭头函数的arguments和this,所以可以直接绑定
            func.apply(this, arguments)
            timer = null
        }, delay)
    }
}

实现 instanceof

  • 函数具有prototype属性,包含constructor和proto
  • 对象有个proto,指向构造函数的prototype属性
    所以以此来查找原型链
    let myInstanceof=(target,origin)=>{
        while(target){
            if(target.__proto__===origin.prototype){
                return true
            }
            target=target.__proto__
        }
        return false
    }

实现new

  • 创建一个新的空对象,把这个对象的__proto__指向构造函数的prototype
  • 将函数调用时的this指向连接到这个对象上
  • 分析函数的返回值
function _new(fn,...args) {
    let obj={}
    obj.__proto__=fn.prototype
    let result=fn.apply(obj,args)
    return typeof result==='object'?result:obj
}
发布日期:
分类:随笔

发表评论

您的电子邮箱地址不会被公开。