微一案笔试题分享

1 哪些操作会引起内存泄漏,如何发现

一些常见的内存泄露代码

// 意外的全局变量
functuon foo () { bar = 1} //函数里直接对未定义的变量赋值,导致变量存在顶部Window中,内存垃圾无法回收

//闭包变量被引用导致无法被回收
function fun2() {
    var obj = { a: 2 }
    return obj;
}	
var a =  fun2()

//被遗忘的定时器

function Test()  {  
    this.obj= {};
    this.index = 1;
    this.timer = null;
    var cache = []; // 内部变量,内存隐患...
    this.timer = window.setInterval(() =>{
        this.index += 1; 
        this.obj = {
            val: '_timerxxxxxbbbbxx_' + this.index,
            junk: [...cache]
        };
        cache.push(this.obj);
    }, 1);  
    console.warn("create Test instance..");
}  
test = new Test(); // JS对象开启定时器不断分配内存


...


参考文章:

https://juejin.im/post/5a8e7f6df265da4e832677ec

https://github.com/wengjq/Blog/issues/1

如何查看内存占用情况

web

googol控制台 》 performance 面板 > 勾选 Memory
点击左上角的录制按钮。
在页面上进行各种操作,模拟用户的使用情况。
如果内存占用基本平稳,接近水平,就说明不存在内存泄漏。反之,就是内存泄漏了。

node

console.log(process.memoryUsage()); //node

2 以下代码输出

typeof Vue
typeof React
typeof jQery	

function github Vue

object github React

function github Jquery

ps:话说我写了这么久Vue。还从来没操作过typeof vue。。。。

3 下面代码输出

class F {
  init () {
		console.log(1)
  }
}
var f = new F()

F.prototype.init = function () {
  console.log(2)
}

f.init() //2

4 如何在数组头部、尾部、中部增加/删除

头部:unshift / shift

中部:splice / concat

尾部: push / pop

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

5 手写防抖/节流 实现

function throttleAndDebounce(fn, delay, isThrottle) {
  let lastCallTime = 0, timer = null;
  return  (...args) => {
    if (isThrottle) {
      const now = Date.now()
      if (now - lastCallTime < delay) return
      lastCallTime = now
      fn(...args)
    } else {
      if (timer) clearTimeout(timer)
      timer = setTimeout( () => {
        fn(...args)
      }, delay)
    }
  }
}

6 filter/reduce 实现数组去重

var arr = [1,2,1]

arr.filter( (it, idx, arr) => {
  return arr.indexOf(it) === idx
})

// reduce
var reducer = (arr, cur) => {
  if ( arr.length === 0 || arr[arr.length - 1] !== cur) {
    arr.push(cur)
  }
  return arr
}
arr.sort().reduce(reducer, [])

7 原生实现 上传base64 图片

<input id="file" type="file" />
var file = document.getElementById('file').files[0]
var reader = new FileReader()
    reader.onload = function (e) {
      $.post('/upload' , { "base64": e.target.result } , function () {})
    }
    reader.readAsDataURL(file)

8 写成3种前端下载文件方式

参考: https://segmentfault.com/a/1190000016906180

ps:这也算!!?浏览器打开。。。内心一度崩溃,真的是为了面试而面试。。

9 手写promise 实现

参考:

https://www.jianshu.com/p/43de678e918a

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise#浏览器兼容性

10 vue实现数据绑定有什么缺陷?作者为什么改用proxy实现

参考:https://zhuanlan.zhihu.com/p/50547367

后记

有些问题 我没给出答案,只给出一些参考链接,主要是才疏学浅,不能给出一个绝对完美的答案;或者答案的内容量可以再写一篇深入专研的文章,大家有什么好的意见或者文章错误可以留言补充;欢迎技术交流

ps:一年没面试了第一次做这种笔试题,我表示一个笔都好久没握过的人瑟瑟发抖。。。建议大家不要裸辞。。这个夏天有点冷。。。

如果觉得本文对你有所帮助,就star一下吧~大传送之术! 我的博客Github

原文地址:https://www.cnblogs.com/buzhiqianduan/p/10712619.html