常见前端面试题

箭头函数与普通函数的区别

  • 箭头函数语法比普通函数更加简洁,但箭头函数中没有arguments,所以形参可以使用展开运算符 (...args) => {console.log(args)}获取
  • 箭头函数没有自己的this,他的this事继承函数所处上下文中的this,使用call,apply等任何方式都无法改变this的指向
  • 箭头函数不能被new执行,因为箭头函数没有prototype

如何把一个字符串的大小写取反

小转大 toUpperCase()
大转小 toLowerCase()
let str = 'AbC'
str = str.replace(/[a-zA-Z]/g,content => {
    return content.toUpperCase() === content ? content.toLowerCase() : content.toUpperCase()
})

数组扁平化

let arr = [1,[2,[3,5]],4]
arr.flat(Infinity)
// [1,2,3,5,4]

手写一个new

function _new(Fn,...args){
    // 创建一个空对象,让他的原型链指向Fn.prototype
    let obj = {}
    obj.__proto__ = Fn.prototype
    // 也可以使用下面这一行代码完成上面的两步操作
    let obj = Object.create(Fn.prototype)
    Fn.call(obj,...args)
    return obj
}

对象调用push

let obj = {
    2: 3,
    3: 4,
    length: 2,
    push: Array.prototype.push
}
obj.push(1)
obj.push(2)
console.log(obj)

旋转数组

function rotate(k){
    if (k < 0 || k === 0 || k === this.length) return this
    if (k > this.length) k = k % this.length
    return this.slice(-k).concat(this.slice(0,this.length-k))
}
Array.prototype.rotate = rotate
let arr = [1,2,3,4,5,6,7]
arr.rotate(3)

手写一个bind

~function(){
    function myBind(context = window,...outerArg){
        let that = this
        return function(...innerArg){
            that.call(context,...outerArg.concat(innerArg))
        }
    }
    Function.prototype.myBind = myBind
}()
function fn(...args){
  console.log(this,args)
}
document.body.onclick = fn.myBind(obj,100,200)

函数柯理化,请实现一个add函数,满足以下功能
add(1) // 1
add(1)(2) // 3
add(1)(2)(3) // 6
add().....()
add(1)(2,3) // 6
add(1,2)(3) // 6
add(1,2,3)

function currying(fn,length){
    length = length || fn.length
    return function(...args){
        if(args.length >= length){
            return fn(...args)
        }
        return currying(fn.bind(null,...args),length - args.length)
    }
}
function add(n1,n2,n3){
    return n1 + n2 + n3
}
add = currying(add,3)

你可能感兴趣的:(常见前端面试题)