前端面试题整理

前言

本人并不是技术大牛(但是会一直朝着那个方向前进),本文会分享一些本人在面试过程中遇到的一些比较有意思的前端面试题目,如有不对之处还请各位巨牛批评指正!

Javascript

Q: 使用promise封装一个readfile函数 ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const fs = require('fs')
function pReadFile(filePath){
return new Promise(function(resolve,reject){
fs.readFile(filePath,'utf8',function(err,data){
if(err){
reject(err)
} else {
resolve(data)
}
})
})
}
pReadFile('./data/a.txt')
.then(function(data){
console.log(data)
return pReadFile('./data/b.txt')
})
.then(function(data){
console.log(data)
return pReadFile('./data/c.txt')
})
.then(function(data){
console.log(data)
})

Q:去除连续重复字符串?例:abcdaaabcd 输出abcdabcd ?

1
2
3
4
5
6
7
8
9
10
11
12
13
function str_ (str) {
let result = ''
if (str != '') {
result = str[0];
for (let i = 1; i < str.length; i++) {
if (str[i] != str[i - 1]) {
result += str[i];
}
}
}
else result = '';
return result;
}

Q: 正则将电话号码中间四位变成#号 ?

1
2
3
4
5
6
7
8
// 方式 1: 正则分组
let phone = "18180800880"
let reg = /(\d{3})\d{4}(\d{4})/
phone.replace(reg,"$1****$2")
// 181****0880

// 方式 2:字符串截取
phone.substr(0,3) + "****" + phone.substr(7);

Q: 查看下列代码运行结果 ?

1
2
3
4
5
6
7
8
9
10
11
try {
setTimeout(()=> {
throw new Error('1')
},0)
console.log('222')
} catch(error) {
console.log('333')
console.log(error)
}
// 执行try块中代码,然后执行宏任务代码,
// 将异步任务放到队列中,当宏任务队列执行时抛出异常,但是不会走到catch中

Q: 写出下列代码运行打印结果 ?

1
2
3
4
5
let foo = function() { console.log(1) };
(function foo() {
foo = 10 // 由于foo在函数中只为可读,因此赋值无效
console.log(foo)
}())

Q: 数组拆解: flat: [1,[{a:1},3]] –> [1, {a: 1}, 3] ?

  • 方式 1,缺陷如果元素是对象会报错
1
2
3
Array.prototype.flat = function() {
return this.toString().split(',').map(item => +item )
}
  • 方式 2,es6数组新扩展,参数是维度,可填写无穷大
1
[1,[2,3]].flat(1) ==> [1,2,3]
  • 方式 3,reduce 和 concat
1
2
3
4
5
6
var arr1 = [1,{sas: '222'},3,[1,2,3,4, [2,3,4]]];

function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);

Q: 写一个函数输出: [‘a’, ‘b’, ‘c’, ‘d’] => { a: { b: { c: ‘d’ } } } ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function to_(arr) {
const _arr = arr.reverse()
if (!Array.isArray(_arr)) return {};
return _arr.reduce((item, cur, index, arr) => {
if (index === 0) {
item = {
[arr[index + 1]]: cur
};
return item
};
if (index === 1) return item;
item = { [cur]: item };
return item;
}, {})
}

Q: 封装一个Array.filter方法 ?

  • 1.使用Array.reduce方法封装,还有其他方法,希望大家帮忙补充!
1
2
3
4
5
6
function Filter(arr, callback) {
return arr.reduce((item, cur, index, arr) => {
if (callback(cur, index, arr)) item.push(cur)
return item;
}, [])
}

Q: 什么是防抖和节流?有什么区别?如何实现 ?

  • 防抖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
// 思路:每次触发事件时都取消之前的延时调用方法
function debounce(fn) {
let timeout = null; // 创建一个标记用来存放定时器的返回值
return function () {
clearTimeout(timeout); // 每当用户输入的时候把前一个 setTimeout clear 掉
timeout = setTimeout(() => { // 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
fn.apply(this, arguments);
}, 500);
};
}
function sayHi() {
console.log('防抖成功');
}

var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi)); // 防抖
  • 节流
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
// 思路:每次触发事件时都判断当前是否有等待执行的延时函数

function throttle(fn) {
let canRun = true; // 通过闭包保存一个标记
return function () {
if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
canRun = false; // 立即设置为false
setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中
fn.apply(this, arguments);
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
canRun = true;
}, 500);
};
}
function sayHi(e) {
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));

Q: 创建一个从1——5数组 ?

  • 字面量
1
2
3
const arr = [1,2,3,4,5];
var arr = [1,2,3,4,5];
let arr = [1,2,3,4,5];
  • 方法
1
2
3
4
5
6
7
8
9
10
11
12
const arr = Array.of(1,2,3,4,5)
const arr = Array.from('12345').map(e=> Number(e))
const arr = Array(5).map((e,index)=>{
return index + 1
})
const arr = [...Array(5)].map((e,i)=> i+ 1)
const arr = '12345'.split('').map(e=> Number(e))
const arr = Array(5).fill(0).map((e,i)=> i+ 1)
const arr = Array.from(Array(5))
arr.forEach((e,i)=>{
arr.fill(i + 1,i, i + 1)
})

Q: 给定一个整数数组 nums 和一个目标值 target ,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标 ?

  • 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 给定 nums = [2, 7, 11, 15], target = 9

// 因为 nums[0] + nums[1] = 2 + 7 = 9
// 所以返回 [0, 1]

// 第一种
let nums = [2, 7, 11, 15],
target = 26;

function getSumIndex(arr1, sum) {
let i = 0;
while (i < arr1.length) {
const j = arr1.slice(i + 1).findIndex(item => arr1[i] + item === sum);
if (j !== -1) {
console.log([i, i + 1 + j]);
return [i, i + 1 + j];
} else {
i++;
}
}
console.log("[]");
return [];
}

// 第二种

var getSumIndex = function(nums, target) {
let map = new Map()
for(let i = 0; i< nums.length; i++) {
let k = target-nums[i]
if(map.has(k)) {
return [map.get(k), i]
}
map.set(nums[i], i)
}
return [];
};


getSumIndex(nums, target);
  • 附leetcode地址:leetcode

Q: [4,3,2,7,8,2,3,1,2,3,4,5,3,8] ==> [2,3,4,8] ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function handlerData (arr) {
let obj = {}
if(!Array.isArray(arr)) return []
return arr.reduce((item,cur)=>{
if(obj[cur]) {
obj[cur] += 1
// 其实这两还可以使用new Set
if(!item.includes(cur)) {
item.push(cur)
}
} else {
obj[cur] = 1
}
return item
},[])
})

Q: let、const、var区别 ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 查看下列输出
var b = 2;
if (true) {
let a = 2;
var b = 3;
var c = 4;
const d = 5;
}

console.log(a); // undefined
console.log(b); // 3
console.log(c); // 4
console.log(d); // undefined
var d = 6;
var a;

// 输出
// undefined
// 3
// 4
// undefined

Q: 实现一个new、bind、apply、call方法 ?

  • 实现new关键字
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// 第一种
function newObj(Obj, ...args) {
// 创建对象
let newObj = Object.create({})
// 将传入的构造函数原型赋值给新创建的对象的原型链上
newObj.__proto__ = Obj.prototype
// 改变this指向
Obj.apply(newObj, args)
return newObj
}

// 第二种
function objectFactory() {
// 创建对象
const obj = new Object(),
// 获取传入参数第一个为要new的构造函数
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
// this转向
const ret = Constructor.apply(obj, arguments);
return typeof ret === 'object' ? ret : obj;
};
  • 实现call和apply方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// call
Function.prototype.call_ = function(...args) {
const context = args[0] || window
context.fn = this
const args_ = args.length > 1 ? args.splice(1) : args
context.fn(...args_)
delete context.fn
}
// apply
Function.prototype.apply_ = function(...args) {
const context = args[0] || window
context.fn = this
const args_ = args.length > 1 ? args.splice(1) : args
context.fn(args_)
delete context.fn
}
  • 实现bind方法
1
2
3
4
5
6
7
Function.prototype.bind2 = function (...args) {
const self = this;
return function (...args_) {
this.prototype = self.prototype;
return self.apply(this, args.concat(args_));
}
}

Q: 实现一下 element.js ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const el = new require('./element.js');
const ul = el('ul', {id: 'list'}, [
el('li', {class: 'item'}, ['Item 1']),
el('li', {class: 'item'}, ['Item 2']),
el('li', {class: 'item'}, ['Item 3'])
])
const ulRoot = ul.render();
document.body.appendChild(ulRoot);

// dom输出:
<ul id='list'>
<li class='item'>Item 1</li>
<li class='item'>Item 2</li>
<li class='item'>Item 3</li>
</ul>

// 实现方案
class El {
constructor(el, attr, children) {
this.data = this.handlerData({ el, attr, children })
return this
}
/*
* 创建VDom元素
*/
render() {
return this.createdElement(this.data)
}
createdElement({ el, attr, children }) {
const node = document.createElement(el)
if (typeof attr === 'object' && Object.keys(attr).length > 0) {
for (const key of Object.keys(attr)) {
if (key) {
node[key] = this.handlerAttr(node, key, attr[key])[key]
}
}
}
if (Array.isArray(children)) {
for (const item of children) {
if (typeof item === 'object') {
node.appendChild(this.createdElement(item.data))
} else {
const textNode = document.createElement('span')
textNode.innerHTML = item
node.appendChild(textNode)
}
}
}
return node
}
handlerAttr(node, key, value) {
let obj = {
style(value_) {
node.style = value_
return node
},
class(value_) {
if (typeof value_ === 'string') {
node.classList.add(value_)
}
return node
},
// 直接赋值操作
miss(value_) {
node[key] = value_
return node
}
}
return obj[key] ? obj[key](value) : obj['miss'](value)
}
handlerData({ el, attr, children }) {
return {
el, attr, children
}
}
}

Q: 请写出格式化以下字符串的函数?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 将字符串"I'm?$$$driving$??$to$?beijing$?$$after$breakfast"格式化为"I'm driving to Beijing after breakfast"
// 1.我们需要的内容只有大小写英文字母和“'”这个单引号
// 2.假如乱码特殊字符的最后一位是=== "?",则他的下一位如果是字母肯定为大写

function handler(str) {
let index = 0
return Array.from(str).reduce((item,cur,_index,arr)=>{
if(cur === '$' && arr[_index + 1] === '?' && /[A-Za-z]/g.test(arr[_index + 2])) {
index = _index + 2
}
if(cur === '$' || cur === '?') {
item += ' '
} else {
if( index === _index) {
item += cur.toUpperCase()
} else {
item += cur
}
}
return item.replace(/(\s)+/g,'$1') // 替换重复空格
},'')
}

Q: 实现一下$on/$off/$emit ?

  • 就是让我们实现下vue的订阅者模式,其实双向绑定也是这样实现的!
  • 这三个函数主要依赖的是一个大的依赖收集器来做的!(PS:具体实现请看下边!)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class dep {
constructor() {
// 因为订阅者有n个并且实现逻辑都不一样,所以采用对象数组形式
this.events = {}
}
getType(val) {
// 不区分大小写
const str = Object.prototype.toString.call(val);
return /^\[Object ?(.*)\]$/i.exec(str)[1].toLowerCase()
}
// 订阅者
$on(eventName, callback) {
if (!eventName) {
throw new Error('event name can\'t empty')
}
if (this.getType(eventName) === 'string') {
if (Reflect.has(this.events, eventName) && Array.isArray(this.events[eventName])) {
this.events[eventName].push(callback)
} else {
Reflect.set(this.events, eventName, [callback])
}
}
if (this.getType(eventName) === 'array') {
for (let item of eventName) {
this.$on(item, callback)
}
}
}
// 订阅注销
$off(eventName, callback) {
if (arguments.length <= 0) {
this.events = Object.create(null)
}
if (eventName && !callback) {
Reflect.deleteProperty(this.events, eventName)
}
if (callback) {
if(!Reflect.has(this.events, eventName)) {
this.$on(eventName, callback)
return
}
let cbs = this.events[eventName]
let i = cbs.length
while (i--) {
let cb = cbs[i]
// cb.fn === fn 针对once绑定的事件
if (cb === callback || cb.fn === callback) {
cbs.splice(i, 1)
break
}
}
}
}
// 通知订阅
$emit(eventName, ...args) {
if (!eventName || (this.getType(eventName) !== 'string' && this.getType(eventName) !== 'array')) {
throw new Error('event name not a string/array')
}
if (this.getType(eventName) === 'string') {
if (!Reflect.has(this.events, eventName)) {
return
}
for (let cb of this.events[eventName]) {
cb.call(this, ...args)
}
}
if (this.getType(eventName) === 'array') {
for (let eventName_ of eventName) {
this.$emit(eventName_, ...args)
}
}
}
}

Q: 数据结构(栈和堆)和数据类型 ?

  • 基本数据类型
    • js基本数据类型包括:undefined,null,number,boolean,string.基本数据类型是按值访问的,就是说我们可以操作保存在变量中的实际的值
    • 基本数据类型的值是不可变的
    • 基本数据类型不可以添加属性和方法
    • 基本数据类型的赋值是简单赋值
    • 基本数据类型的比较是值的比较
    • 基本数据类型是存放在栈区的
  • 引用类型
    • 引用类型的值是可以改变的
    • 引用类型可以添加属性和方法
    • 引用类型的赋值是对象引用
    • 引用类型的比较是引用的比较
    • 引用类型是同时保存在栈区和堆区中的
  • 基本包装类型(包装对象)
  • 参考资料: 基本数据类型和引用类型的区别详解

CSS

Q:弹性盒子中 flex: 0 1 auto 表示什么意思?

1
2
3
4
三个参数分别对应的是 flex-grow, flex-shrink 和 flex-basis,默认值为0 1 auto。
1.flex-grow属性定义项目的放大比例,默认为0,即如果存在剩余空间,也不放大。
2.flex-shrink属性定义了项目的缩小比例,默认为1,即如果空间不足,该项目将缩小。
3.flex-basis属性定义了在分配多余空间之前,项目占据的主轴空间(main size)。

webpack

Q: webpackloaderplugin 的区别是什么 ?

  • 这里引用官方文档原文:
1
While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.
  • 网友解释
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# loader:让webpack能够处理非js文件(自身职能理解js),然后你就可以利用 webpack 的打包能力,对它们进行处理。
例如:css-loader、style-loader、postcss-loader、sass-loader

# plugins:从打包优化和压缩,一直到重新定义环境中的变量.
例如:uglify-webpack-plugin、clean-webpack-plugin、babel-polyfill

# 相对于loader转换指定类型的模块功能,plugins能够被用于执行更广泛的任务比如打包优化、文件管理、环境注入等……

# webpack 是由nodejs编写的前端资源加载/打包工具,由nodejs提供了强大的文件处理,IO能力。
loader: 是一个nodejs 函数模块, 传入resource file 或者sourceMap json 结果,读取文件,将文件处理为String 或者 Buffer 格式,然后传给compiler 或者下一个loader.
plugin: 是能够参与到compilation process的自定义函数,通过hook到每一个编译(compiler)中,触发关键事件或处理。

# 如何自定义webpack插件:

# JavaScript 命名函数
在插件函数prototype 上定义一个apply 方法
定义一个绑定到webpack 自身的hook
处理webpack内部特定数据
功能完成后调用webpack 提供的回调


一、webpack的打包原理

识别入口文件
通过逐层识别模块依赖(Commonjs、amd或者es6的import,webpack都会对其进行分析,来获取代码的依赖)
webpack做的就是分析代码,转换代码,编译代码,输出代码
最终形成打包后的代码
二、什么是loader

loader是文件加载器,能够加载资源文件,并对这些文件进行一些处理,诸如编译、压缩等,最终一起打包到指定的文件中处理一个文件可以使用多个loader,loader的执行顺序和配置中的顺序是相反的,即最后一个loader最先执行,第一个loader最后执行,第一个执行的loader接收源文件内容作为参数,其它loader接收前一个执行的loader的返回值作为参数,最后执行的loader会返回此模块的JavaScript源码

三、什么是plugin

在webpack运行的生命周期中会广播出许多事件,plugin可以监听这些事件,在合适的时机通过webpack提供的API改变输出结果。

四、loader和plugin的区别

对于loader,它是一个转换器,将A文件进行编译形成B文件,这里操作的是文件,比如将A.scss转换为A.css,单纯的文件转换过程
plugin是一个扩展器,它丰富了webpack本身,针对是loader结束后,webpack打包的整个过程,它并不直接操作文件,而是基于事件机制工作,会监听webpack打包过程中的某些节点,执行广泛的任务

网络请求方面

Q: 谈谈 cookie、localStorage 以及 sessionStorage 区别,以及cookie 为什么不建议用

  • 三者的异同:上面的使用方式说好了,下面就唠唠三者之间的区别,这个问题其实很多大厂面试的时候也都会问到,所以可以注意一下这几个之间的区别。生命周期:cookie:可设置失效时间,没有设置的话,默认是关闭浏览器后失效localStorage:除非被手动清除,否则将会永久保存。
  • sessionStorage: 仅在当前网页会话下有效,关闭页面或浏览器后就会被清除。
  • 存放数据大小:cookie:4KB左右
  • localStorage和sessionStorage:可以保存5MB的信息。
  • http请求:cookie:每次都会携带在HTTP头中,如果使用cookie保存过多数据会带来性能问题
  • localStorage和sessionStorage:仅在客户端(即浏览器)中保存,不参与和服务器的通信
  • 易用性:cookie:需要程序员自己封装,源生的Cookie接口不友好
  • localStorage和sessionStorage:源生接口可以接受,亦可再次封装来对Object和Array有更好的支持
  • 应用场景:从安全性来说,因为每次http请求都会携带cookie信息,这样无形中浪费了带宽,所以cookie应该尽可能少的使用,另外cookie还需要指定作用域,不可以跨域调用,限制比较多。但是用来识别用户登录来说,cookie还是比storage更好用的。其他情况下,可以使用storage,就用storage。
  • storage在存储数据的大小上面秒杀了cookie,现在基本上很少使用cookie了,因为更大总是更好的,哈哈哈你们懂得。
  • localStorage和sessionStorage唯一的差别一个是永久保存在浏览器里面,一个是关闭网页就清除了信息。localStorage可以用来夸页面传递参数,sessionStorage用来保存一些临时的数据,防止用户刷新页面之后丢失了一些参数。