近期准备的面试题-1

75 阅读1分钟

手写代码

数组扁平化

function flat(arr){
    let res = []
    for(let item of arr){
        if(item instanceof Array){
            res.push(...flat(item))
        }
        else{
            res.push(item)
        }
    }
    return res
}

演示原型链

function A(){
    /* ... */
}

let a = new A()
a.__proto__ == A.prototype // true
Object.getPrototypeOf(a) == A.prototype // true
a.constructor == A // true
A.prototype.constructor == A // true
true == a instanceof A // true
typeof a == 'object' // true

new运算符

function myNew(constructor,...args) {
    let res = {}
    Object.setPrototypeOf(res,constructor.prototype)
    let outcome = constructor.call(res,...args)
    if(outcome instanceof Object) return outcome
    return res
}

函数柯里化

// 处理有限个参数的函数
function Curry_1(fn){
    return function curried(...args){
        if(args.length >= fn.length){
            return fn.apply(this,args)
        }
        return function(...restArgs){
            return curried.apply(this,args.concat(restArgs))
        }
    }
}

// 处理不定参数个数的函数
function Curry_2(fn){
    let args = []
    return function curried() {
        if(arguments.length !== 0){
            args.push(...arguments)
            return curried
        }
        return fn.apply(this,args)
    }
}
// 调用方式与正常柯里化函数略有不同
// 参数不定长的求和函数
function sum(){
    return [...arguments].reduce((pre,cur) => pre + cur)
}
const curriedSum = Curry_2(sum)
let res = curriedSum(1)(2)(3)() // 需要多加一个空括号表示调用
console.log(res) // 打印:‘6’

可以判断所有类型的函数(包括引用类型)

function myTypeof(obj){
    return Object.prototype.toString.call(obj).slice(8,-1)
}

instanceof运算符

function myInstanceof(left,right){
    let proto = Object.getPrototypeOf(left)
    while(proto){
        if(proto == right.prototype) return true
        proto = Object.getPrototypeOf(proto)
    }
    return false
}

深拷贝函数(并非最完善版本)

function deepCopy(obj) {
    // 处理null或非对象类型
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    // 处理数组
    if (Array.isArray(obj)) {
        return obj.map(item => deepCopy(item));
    }
    // 处理普通对象
    const result = {};
    for (let key in obj) {
        // 只复制对象自身的属性
        if (obj.hasOwnProperty(key)) {
            result[key] = deepCopy(obj[key]);
        }
    }
    return result;
}

节流函数(delay时间内,仅执行第一次)

function throttle(fn, delay) {
    let curTime = 0;
    return function(...args) {
        const now = Date.now();
        if (now - curTime >= delay) {
            curTime = now;
            fn.apply(this, args); // 修复this指向
        }
    };
}

防抖函数(每次触发重新计时delay时长)

function debounce(fn, delay) {
    let timer = null;
    return function(...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args); // 修复this指向
        }, delay);
    };
}