从两道面试题考察js基础

244 阅读2分钟

1. 前言

     金三银四下, 本想借助万能的微信好友求个内推, 未曾想有个小伙伴直接甩我2道面试题说看看js基础, 故有了这篇文章.

2. 编程题一

// html部分
<div id="app" style="width: 100px; height: 100px;background-color: bisque;">一道面试题</div>

// js部分
const dom = document.getElementById('app')
const throttle = function(fun, time) {
    let timer = ''
    console.log('闭包前输出this:', this)
    return function() {
        if(timer) {
            return
        }
        console.log('闭包内this指向', this)
        timer =  setTimeout(() => {
            timer = null
            fun()
        }, time)
    }
}

dom.addEventListener(
    'mousemove',
    throttle(function() {
        console.log('mousemove中this指向', this)
    }, 1000/30)
)

问题: 请根据上述代码, 写出3次console.log的输出分别是什么? image.png
这道题主要考下面这些基础:

  • 事件流
  • 闭包
  • this的指向

衍生问题: 若希望在mousemove的时候需要拿到dom结构, 需要怎么改呢?

// 改动点: 
timer =  setTimeout(() => {
    timer = null
    // 若此处是function(){}的写法, 用call()就没用, 需要特别留意。
    fun.call(this)
}, time)

我们先来看看改动是否有效: image.png
事实证明是有效的, 那么这个问题又主要考察什么呢?
这个问题主要考下面这些基础:

  • 箭头函数this的指向
  • 如何改变this的指向

衍生问题: 若setTimeout里是个普通函数, 仍是希望实现在mousemove中拿到dom结构, 那又是需要怎么改呢?

// 改动点
// 新增语句const _that = this
const _that = this
timer =  setTimeout(function () {
    timer = null
    fun.call(_that)
}, time)

3. 编程题二

题目: 假设我需要从[{},{},{}]数组中高频率的从这个数组中取值, 要怎么做性能优化呢?
解答思路:

  • 新建一个obj对象
  • 遍历该数组, 判断当前item的key是否在obj中存在, 若是则直接从obj取值; 若不是则将当前item相关信息存储在obj中, 便于下次直接从内存中拿取, 不再需要遍历数组.
// 大概设想demo, 不一定是最优解, 只是说明思路
// xxx表示的是对象数组中的key, 用于取值判断用
function getInfo(arr = [], obj = {}) {
    let tmpObj = {}
    let res
    let length = arr.length || 0
    for(let i = 0; i < length; i++) {
        const item = arr[i]
        if(tmpObj[item.xxx]) {
            // 存在则直接从tmpObj读取信息、不再遍历
            res = tmpObj[item.xxx]
            break
        }else if(item.xxx === obj.xxx){
            // 不存在则取到值之后更新在tmpObj里面、便于下次读取从tmpObj拿
            tmpObj[item.xxx] = {
                index: i,
                ...item
            }
            res = tmpObj[item.xxx]
            break
        }
    }
    return res
}
// list的时间复杂度是O(n), map的时间复杂度是O(1).

4. 最后

     js基础是考察前端基础是否扎实很关键的一个点, 注重js基础完善, 希望大家都能如愿找到合适的工作.