JavaScript常见笔试题整理

手写 快排实现

      const quickSort = (arr, low, high) => {
        if (low < high) {
          let par = partition(arr, low, high)
          quickSort(arr, low, par - 1) //注意下标起始,否则会造成死循环
          quickSort(arr, par + 1, high)
        }
        return arr
      }

      const partition = (arr, low, high) => {
        let pivot = arr[low]
        while (low < high) {
          while (arr[high] > pivot && high > low) {
            high--
          }
          arr[low] = arr[high]
          while (arr[low] <= pivot && high > low) {
            low++
          }
          arr[high] = arr[low]
        }
        arr[low] = pivot
        return low
      }

手写冒泡排序实现以及优化

      const bubbleSort = (arr) => {
        for (let j = 0; j < arr.length; j++) {
          let flag = false
          for (let i = 0; i < arr.length - 1 - j; i++) {
            if (arr[i] > arr[i + 1]) {
              flag = true
              let tmp = arr[i]
              arr[i] = arr[i + 1]
              arr[i + 1] = tmp
            }
          }
          if (!flag) break
        }
        return arr
      }

判断一颗树是否为搜索二叉树和完全二叉树

function judgeIt( root ) {
    let leftVal = Number.MIN_VALUE
    let rightVal = Number.MAX_VALUE
    let res  = []
    res[0] = searchTree(root,leftVal,rightVal)
    res[1] = CBT(root)
    return res
}

const searchTree = (root,leftVal,rightVal)=>{
    if(!root) return true
    if(root.val <= leftVal || root.val >= rightVal) return false
    return searchTree(root.left,leftVal,root.val) && searchTree(root.right,root.val,rightVal)
}

const CBT = (root)=>{
    if(!root) return true
    const queue = []
    let flag = false
    queue.push(root)
    while(queue.length){
        let tmp = queue.shift()
        let left = tmp.left
        let right = tmp.right
        if(!left && right) return false
        if(flag && !(!left && !right)) return false
        if(left) queue.push(left)
        if(right) queue.push(right)
        if(!flag && (!left || !right)) flag = true
    }
    return true
}

手写 instanceof 实现


      const myInstanceof = (A, B) => {
        let p1 = A._proto_
        let p2 = B.prototype
        while (true) {
          if (p1 == null) {
            return false
          }
          if (p1 == p2) {
            return true
          }
          p1 = p1._proto_
        }
      }

在这里插入图片描述

手写一个基于发布订阅模式的js事件处理中心(EventEmitter)

class EventEmitter {
  constructor() {
    this.events = {}
  }
  on = (event, callback) => {
    if (this.events[event]) {
      this.events[event].push(callback)
    } else {
      this.events[event] = [callback]
    }
  }
  off = (event, callback) => {
    const eventArr = this.events[event]
    eventArr.filter((name) => name != callback)
    this.events[event] = eventArr
  }
  once = (event, callback) => {
    function one() {
      callback.apply(this, arguments)
      this.off(event, one)
    }

    this.on(event, one)
  }

  emit = (event, arguments) => {
    this.events[event].forEach((callback) => {
      callback.apply(this, arguments)
    })
  }
}

手写render函数

  <body>
    <div id="text"></div>
  </body>
  <script>
    var vnode = {
      tag: 'ul',
      props: {
        class: 'list',
        on: {
          // 传入点击事件
          click: (e) => {
            console.log(e)
          },
        },
      },
      text: '',
      children: [
        {
          tag: 'li',
          props: {
            class: 'item',
          },
          text: '',
          children: [
            {
              tag: undefined,
              props: {},
              text: '牛客网',
              children: [],
            },
          ],
        },
        {
          tag: 'li',
          props: {},
          text: '',
          children: [
            {
              tag: undefined,
              props: {},
              text: 'nowcoder',
              children: [],
            },
          ],
        },
      ],
    }
    const _createElm = (vnode) => {
      const { tag, props, text, children } = vnode
      let node = document.createElement(tag)
      for (let prop in props) {
        if (prop === 'on') {
          let events = props[prop]
          for (let key in events) {
            node.addEventListener(key, (e) => {
              events[key](e)
            })
          }
        } else {
          node.setAttribute(prop, props[prop])
        }
      }
      node.innerHtml = text
      children.forEach((element) => {
        node.appendChild(_createElm(element))
      })
      return node
    }
    let text = document.querySelector('#text')
    text.appendChild(_createElm(vnode))
  </script>

手写lodash_get方法

    //手写lodash get 方法
    const object = { a: [{ b: { c: 3 } }] }
    const path = ['a', '0', 'b', 'c']

    function myGet(obj, path, defaultValue) {
      let res = obj
      path.forEach((k) => {
        let value = res[k]
        if (value) {
          res = value
        } else {
          res = defaultValue
        }
      })
      return res
    }
    console.log(myGet(object, path, 'NULL'))

手写call apply bind函数

    Function.prototype.myCall = function (context, ...args) {
      context = context === 'undefined' ? window : Object(context)
      let res = null
      let fn = Symbol()
      context[fn] = this
      res = context[fn](...args)
      delete context[fn]
      return res
    }

    Function.prototype.myApply = function (context, arguments) {
      context = context === 'undefined' ? window : Object(context)
      let res = null
      let fn = Symbol()
      context[fn] = this
      res = context[fn](...arguments)
      delete context[fn]
      return res
    }

      Function.prototype.myBind = function () {
        let arr = Array.prototype.slice.call(arguments)
        let self = arr.shift()
        let fn = this
        return function () {
          return fn.apply(self, arr)
        }
      }

手写节流防抖函数

// 防抖——事件触发的N秒时间后才执行回调

function debounce(fn, delay) {
  var timer
  return function () {
    let that = this
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

//节流——事件触发的N秒内只执行一次

function throttle(fn, delay) {
  var timer
  return function () {
    let that = this
    let args = arguments
    if (timer) {
      return
    }
    timer = setTimeout(function () {
      fn.apply(that, args)
      timer = null
    }, delay)
  }
}

手写AJAX

  • axio是对XMLHttpRequest的封装,需要引入axios库
  • fetch是一种新的获取接口资源的方式,原生浏览器支持
  • axios总体优于fetch
    //ajax简易写法
    function ajax1(url) {
      const request = new XMLHttpRequest()
      request.open('GET', url)
      request.onreadystatechange = function () {
        if (request.readyState === 4) {
          if (request.status >= 200 && request.status < 300) {
            let res = request.responseText()
            return JSON.parse(res)
          }
        }
      }
      request.send()
    }

    //ajax promise封装
    function ajax2(url) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.onreadystatechange = () => {
          if (xhr.readyState !== 4) return
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(xhr.response)
          } else {
            reject(new Error(xhr.response))
          }
        }
        xhr.send()
      })
    }

手写promise

    class MyPromise {
      constructor(func) {
        this.value = null
        this.error = null
        this.status = 'pending'
        this.resolveStacks = []
        this.rejectStacks = []
        try {
          func(this.resolve, this.reject)
        } catch (error) {
          this.reject(error)
        }
      }
      resolve = (value) => {
        if (this.status === 'pending') {
          this.status = 'fulfilled'
          this.value = value
          this.resolveStacks.forEach((cb) => cb())
        }
      }
      reject = (error) => {
        if (this.status === 'pending') {
          this.status = 'rejected'
          this.error = error
          this.rejectStacks.forEach((cb) => cb())
        }
      }
      then = (onFulfilled, onRejected) => {
        return new MyPromise((resolve, reject) => {
          onFulfilled =
            typeof onFulfilled === 'function' ? onFulfilled : () => {}
          onRejected = typeof onRejected === 'function' ? onRejected : () => {}
          if (this.status === 'pending') {
            this.resolveStacks.push(() => {
              onFulfilled(this.value)
            })
            this.rejectStacks.push(() => {
              onRejected(this.error)
            })
          }
          if (this.status === 'fulfilled') {
            onFulfilled(this.value)
          }
          if (this.status === 'rejected') {
            onRejected(this.error)
          }
        })
      }
    }

    const promise = new MyPromise((resolve, reject) => {
      setTimeout(() => {
        resolve('成功')
      }, 1000)
    })
    promise.then((data) => {
      console.log(data)
    })

手写promise.all promise.race

    let promise1 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(0)
      }, 0)
    })
    let promise2 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(1)
      }, 1000)
    })
    let promise3 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(2)
      }, 2000)
    })
    let promise4 = new Promise((resolve, reject) => {
      reject('error')
    })

    Promise.myAll = (arr) => {
      return new Promise((resolve, reject) => {
        let res = []
        if (!arr.length) {
          resolve(res)
        } else {
          let count = 0
          for (let i = 0; i < arr.length; i++) {
            Promise.resolve(arr[i]).then(
              (data) => {
                res[i] = data
                if (count++ === arr.length - 1) {
                  resolve(res)
                }
              },
              (err) => {
                reject(err)
              }
            )
          }
        }
      })
    }

    Promise.myRace = (arr) => {
      return new Promise((resolve, reject) => {
        if (!arr.length) {
          resolve([])
        } else {
          for (let i = 0; i < arr.length; i++) {
            Promise.resolve(arr[i]).then(
              (data) => {
                resolve(data)
              },
              (err) => {
                reject(err)
              }
            )
          }
        }
      })
    }

    let arr = [promise1, promise2, promise3, promise4, 4]
    Promise.myAll(arr)
      .then((data) => {
        console.log(data)
      })
      .catch((err) => {
        console.log(err)
      })
    Promise.myRace(arr)
      .then((data) => {
        console.log(data)
      })
      .catch((err) => {
        console.log(err)
      })

promise js事件循环执行顺序

const promise = new Promise((resolve,reject)=>{
    console.log(1);
    resolve();
    console.log(2);
    reject()
})
setTimeout(()=>{console.log(5)},0)
promise.then(()=>{console.log(3)})
.then(()=>{console.log(6)})
.catch(()=>{console.log(7)})
console.log(4)

// 1 2 4 3 6 5
const first = () => (new Promise((resolve, reject) => {
    console.log(3);
    let p = new Promise((resolve, reject) => {
        console.log(7);
        setTimeout(() => {
            console.log(5);
            resolve();
        }, 0);
        resolve(1);
    });
    resolve(2);
    p.then((arg) => {
        console.log(arg);
    });
}));
first().then((arg) => {
    console.log(arg);
});
console.log(4);


//3 7 4 1 2 5
console.log(1);
new Promise(resolve => {
    resolve();
    console.log(2);
}).then(() => {
    console.log(3);
})
setTimeout(() => {
    console.log(4);
}, 0);
console.log(5);
// 1 2 5 3 4
Promise.resolve()
.then(() => {
    console.log('1');
})
.then(() => {
    console.log('2');
});


setTimeout(() => {
    Promise.resolve()
    .then(() => {
        console.log('3');
    })
    .then(() => {
        console.log('4');
    });
    setInterval(() => {
        console.log('5');
    }, 3000);
    console.log('6');
}, 0);

//1 2 6 3 4 5 5...
setTimeout(function() {
    console.log(1);
}, 0);
console.log(2);
async function s1() {
    console.log(7)
    await s2();
    console.log(8);
}
asycn function s2() {
    console.log(9);
}
s1();
new Promise((resolve, reject) => {
    console.log(3);
    resolve();
    console.log(6);
}).then(() => console.log(4))
console.log(5);

//2 7 9 3 6 5 8 4 1

手写 setTimeout实现

      const mySetTimeout = (fn, timeout, arguments) => {
        let start = new Date()
        const loop = () => {
          let now = new Date()
          let timer = window.requestAnimationFrame(loop)
          if (now - start >= timeout) {
            fn.apply(this, arguments)
            window.cancelAnimationFrame(timer)
          }
        }
        window.requestAnimationFrame(loop)
      }

      function showName() {
        console.log('Hello')
      }
      let timerID = mySetTimeout(showName, 1000)

      //注:这种写法会造成主线程死锁,不建议
      // const mySetTimeout = (fn, timeout, arguments) => {
      //   const start = new Date()
      //   while (1) {
      //     if (new Date() - start >= timeout) {
      //       fn.apply(this, arguments)
      //       break
      //     }
      //   }
      // }

数组扁平化

      arr = [1, [2, [3, [4]]]]

      const _flatten1 = function (arr) {
        return arr
          .toString()
          .split(',')
          .map((item) => {
            Number(item)
          })
      }
      const _flatten2 = function (arr) {
        let res = []
        for (let item of arr) {
          if (Array.isArray(item)) {
            res = res.concat(_flatten2(item))
          } else {
            res = res.concat(item)
          }
        }
        return res
      }
      const _flatten3 = function (arr) {
        return arr.reduce((pre, cur) => {
          return pre.concat(Array.isArray(cur) ? _flatten3(cur) : cur)
        }, [])
      }

不产生新数组删除原数组中的重复数字

      const remove = (arr) => {
        for (let i = 0; i < arr.length; i++) {
          if (arr.indexOf(arr[i]) !== i) {
            arr.splice(i, 1)
            i--
          }
        }
        return arr
      }

翻转字符串里的单词

      const strReverse = (str) => {
        let left = 0,
          right = str.length - 1
        let res = []
        let tmp = ''
        while (str.charAt(left) === ' ') left++
        while (str.charAt(right) === ' ') right--
        while (left <= right) {
          if (str.charAt(left) === ' ' && tmp !== '') {
            res.unshift(tmp)
            tmp = ''
          } else if (str.charAt(left) !== ' ') {
            tmp += str.charAt(left)
          }
          left++
        }
        res.unshift(tmp)
        return res.join(' ')
      }
      let str = ' hello   world! Bye'
      console.log(strReverse(str))

实现单例模式并实现一个单例的注册弹窗

  <body>
    <button id="but">login</button>
  </body>
  <script>
    
    function SingleTon(name) {
      this.name = name
    }
    SingleTon.prototype.getName = function () {
      console.log(this.name)
    }
    const getInstance = (function () {
      var instance
      return function (name) {
        if (!instance) {
          instance = new SingleTon(name)
        }
        return instance
      }
    })()
    const a = getInstance('a')
    const b = getInstance('b')
    console.log(a === b)

    document.getElementById('but').onclick = function () {
      let div = createSingle()
    }
    function createDiv() {
      let div = document.createElement('div')
      div.innerHTML = 'LOGIN'
      document.body.appendChild(div)
      return div
    }

    function getSingle(fn) {
      var result
      return function () {
        if (!result) {
          result = fn.apply(this, arguments)
        }
        return result
      }
    }
    let createSingle = getSingle(createDiv)

继承方式整理

原型链继承

      //原型链继承
      function Father() {
        this.name = 'father'
        this.nums = [1, 2]
        this.sayHi = function () {
          console.log('hi')
        }
      }
      function Son() {
        this.name = 'son'
        this.sayBye = function () {
          console.log('bye')
        }
      }

      Son.prototype = new Father()
      let son1 = new Son()
      console.log(son1.name) //son
      son1.sayHi() //hi
      son1.sayBye() //bye

      //缺点 1:原型中包含的引用值在实例中共享
      //2:子类型在实例时不能传参
      son1.nums.push(3)
      let son2 = new Son()
      console.log(son1.nums, son2.nums) //[1,2,3][1,2,3]

构造函数继承

    // 构造函数继承
      function Father(name) {
        this.name = 'father'
        this.nums = [1, 2]
        this.sayHi = function () {
          console.log('hi')
        }
      }
      function Son() {
        Father.call(this)
      }
      let son1 = new Son()
      son1.nums.push(3)
      let son2 = new Son()
      console.log(son1.nums, son2.nums) //[1,2,3][1,2]
      //优点:1.解决了原型中的引用值在实例中共享的问题。2.子类型在实例时可传参
      //缺点:1.方式必须在构造函数中定义

组合继承

     //组合继承
      function Father(name) {
        this.name = name
        this.nums = [1, 2]
      }
      Father.prototype.sayHi = function () {
        console.log('hi')
      }
      function Son(name, age) {
        Father.call(this, name)
        this.age = age
      }
      Son.prototype = new Father()
      Son.prototype.sayBye = function () {
        console.log('bye')
      }
      //优点:1.通过原型链继承原型上的属性和方法。2.通过构造函数继承实例属性
      //缺点:继承过程中父类构造函数会执行两次,子类实例和子类原型对象会存在两个相同的属性
      let son1 = new Son('A', 3)
      let son2 = new Son('B', 4)
      son1.nums.push(3)
      console.log(son1.nums, son2.nums) //[1,2,3] [1,2]
      son1.sayBye() //bye
      son1.sayHi() //hi

寄生式组合继承

      //寄生式组合继承
      //优化思路:不通过父类构造函数给子类原型赋值
      function Father(name) {
        this.name = name
        this.nums = [1, 2]
      }
      function Son(name, age) {
        Father.call(this, name)
        this.age = age
      }
      Father.prototype.sayHi = function () {
        console.log('hi')
      }

      // let F = function () {}
      // F.prototype = Father.prototype
      // Son.prototype = new F()
      //封装
      function inheritPrototype(Son, Father) {
        let prototype = Object(Father.prototype)
        prototype.constructor = Son
        Son.prototype = prototype
      }
      inheritPrototype(Son, Father)

      Son.prototype.sayBye = function () {
        console.log('bye')
      }

      let son1 = new Son('A', 3)
      console.log(son1)

类继承

      //类继承
      class Father {
        constructor(name) {
          this.name = name
          this.nums = [1, 2]
        }
        sayHi() {
          console.log('hi')
        }
      }
      class Son extends Father {
        constructor(name, age) {
          super(name)
          this.age = age
        }
        sayBye() {
          console.log('bye')
        }
      }
      let son1 = new Son('A', 3)
      console.log(son1)

CSS实现一个三角形

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #triangle {
        width: 0px;
        height: 0px;
        border: 40px solid transparent;
        border-bottom: 80px solid red;
      }
    </style>
  </head>
  <body>
    <div id="triangle"></div>
  </body>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值