饭后闲来无事,把这几年带学生用的一些面试题整合一下,供上!拿走,不客气!应付一般公司的二面基本上是够用了。祝你早日拿到心仪的offer。
css相关
1. 万能居中
1.margin: 0 auto;水平
2.text-align: center;水平
3.行高,垂直
4.表格,center,middle;水平垂直
5.display:table-cell;模拟表格,all
6.绝对定位,50%减自身宽高
7.绝对定位,上下左右全0,margin:auto
8.绝对定位加相对定位。不需要知道宽高
9.IE6,IE7:给父元素设一个font-size:高度/1.14,vertical-align:middle
2. BFC优化
块格式化上下文, 特性:
• 使 BFC 内部浮动元素不会到处乱跑(清除浮动);
• 和浮动元素产生边界(在非浮动元素加margin)。
3. 盒模型哪两种模式?什么区别?如何设置
• 标准模式: box-sizing: content-box(默认); 宽高不包括内边距和边框
• 怪异模式: box-sizing: border-box
4. 常用清除浮动的方法,如不清除浮动会怎样?
当父元素不给高度的时候,内部元素不浮动时会撑开, 而浮动的时候,父元素变成一条线, 造成塌陷.
• 额外标签法(在最后一个浮动标签后,新加一个标签,给其设置clear:both;)(不推荐)
• 父元素添加overflow:hidden; (触发BFC)
• 使用after伪元素清除浮动(推荐使用)
• 使用before和after双伪元素清除浮动
5. 删格化的原理
比如antd的row和col, 将一行等分为24份, col是几就占几份, 底层按百分比实现; 结合媒体查询, 可以实现响应式
6. 纯css实现三角形
// 通过设置border.box
{
width:0px;
height:0px;
border-top:50px solid rgba(0,0,0,0);
border-right:50px solid rgba(0,0,0,0);
border-bottom:50px solid green;
border-left:50px solid rgba(0,0,0,0);
}
7. 高度不定,宽100%,内一div高不确定,如何实现垂直居中?
• verticle-align: middle;
• 绝对定位50%加translateY(-50%)
• 绝对定位,上下左右全0,margin:auto
8. 至少两种方式实现自适应布局
• rem, em
• vh, vw
• 百分比
• 媒体查询
• bs, antd等的栅格布局
9. 设置一段文字的大小为6px
• 谷歌最小12px, 其他浏览器可以更小
• 通过transform: scale实现
10. css菊花图
四个小圆点一直旋转
// 父标签
animation: antRotate 1.2s infinite linear;// 子标签
animation: antSpin 1s infinite linear;@keyframe antSpin {
to {
opacity: 1
}}@keyframe antRotate {
to {
transform: rotate(405)
}}// animation-delay: 逐个延迟0.4s
11. 关于em
<div style="font-size: 20px">
123
<div style="font-size: 2em;width: 2em">456</div>
</div>
// 此时子元素的font-size为40px, 宽度为80px(还要乘以子元素font-size的系数)
12. 关于vh, vw
vw:viewpoint width,视窗宽度,1vw等于视窗宽度的1%。
vh:viewpoint height,视窗高度,1vh等于视窗高度的1%。
vmin:vw和vh中较小的那个。
vmax:vw和vh中较大的那个。
13. Flex布局
• flex-direction控制主副轴
• flex-wrap控制换行(默认不换行)
• flex-flow是上两个的结合
• justify-content主轴对齐方式
• align-items交叉轴对齐方式
14. overflow原理
• overflow: hidden能清除块内子元素的浮动影响. 因为该属性进行超出隐藏时需要计算盒子内所有元素的高度, 所以会隐式清除浮动
• 创建BFC条件(满足一个):
o float的值不为none;
o overflow的值不为visible;
o position的值为fixed / absolute;
o display的值为table-cell / table-caption / inline-block / flex / inline-flex。
15. 实现自适应的正方形:
• 使用vw, vh
• width百分比, height: 0, padding-top(bottom): 50%
16. 标准模式和怪异模式
• document.compatMode属性可以判断是否是标准模式,当 document.compatMode为“CSS1Compat”,是标准模式,“BackCompat”是怪异模式。
• 怪异模式是为了兼容旧版本的浏览器, 因为IE低版本document.documentElement.clientWidth获取不到
• 怪异模式盒模型: box-sizing: border-box; 标准模式: box-sizing: content-box
17. CSS3实现环形进度条
两个对半矩形遮罩, 使用rotate以及overflow: hidden进行旋转
18. css优先级
选择器的特殊性值表述为4个部分,用0,0,0,0表示。
• ID选择器的特殊性值,加0,1,0,0。
• 类选择器、属性选择器或伪类,加0,0,1,0。
• 元素和伪元素,加0,0,0,1。
• 通配选择器*对特殊性没有贡献,即0,0,0,0。
• 最后比较特殊的一个标志!important(权重),它没有特殊性值,但它的优先级是最高的,为了方便记忆,可以认为它的特殊性值为1,0,0,0,0。
JS相关
1. ES5和ES6继承方式区别
• ES5定义类以函数形式, 以prototype来实现继承
• ES6以class形式定义类, 以extend形式继承
2. Generator了解
ES6 提供的一种异步编程解决方案, Generator 函数是一个状态机,封装了多个内部状态。
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';}
var hw = helloWorldGenerator();
调用后返回指向内部状态的指针, 调用next()才会移向下一个状态, 参数:
hw.next()
// { value: 'hello', done: false }
hw.next()
// { value: 'world', done: false }
hw.next()
// { value: 'ending', done: true }
hw.next()
// { value: undefined, done: true }
3. 手写Promise实现
var myPromise = new Promise((resolve, reject) => {
// 需要执行的代码
...
if (/* 异步执行成功 */) {
resolve(value)
} else if (/* 异步执行失败 */) {
reject(error)
}})
myPromise.then((value) => {
// 成功后调用, 使用value值}, (error) => {
// 失败后调用, 获取错误信息error})
4. Promise优缺点
• 优点: 解决回调地狱, 对异步任务写法更标准化与简洁化
• 缺点: 首先,无法取消Promise,一旦新建它就会立即执行,无法中途取消; 其次,如果不设置回调函数,Promise内部抛出的错误,不会反应到外部; 第三,当处于pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成).
极简版promise封装:
function promise () {
this.msg = '' // 存放value和error
this.status = 'pending'
var that = this
var process = arguments[0]
process (function () {
that.status = 'fulfilled'
that.msg = arguments[0]
}, function () {
that.status = 'rejected'
that.msg = arguments[0]
})
return this}
promise.prototype.then = function () {
if (this.status === 'fulfilled') {
arguments[0](this.msg)
} else if (this.status === 'rejected' && arguments[1]) {
arguments[1](this.msg)
}}
5. 观察者模式
又称发布-订阅模式, 举例子说明.
实现: 发布者管理订阅者队列, 并有新消息推送功能. 订阅者仅关注更新就行
6. 手写实现bind
Function.prototype.bind = function () {
// 保存原函数
var self = this
// 取出第一个参数作为上下文, 相当于[].shift.call(arguments)
var context = Array.prototype.shift.call(arguments)
// 取剩余的参数作为arg; 因为arguments是伪数组, 所以要转化为数组才能使用数组方法
var arg = Array.prototype.slice.call(arguments)
// 返回一个新函数
return function () {
// 绑定上下文并传参
self.apply(context, Array.prototype.concat.call(arg, Array.prototype.slice.call(arguments)))
}}
7. 手写实现4种继承
function Father () {}function Child () {}// 1. 原型继承
Child.prototype = new Father()// 2. 构造继承function Child (name) {
Father.call(this, name)}// 3. 组合继承function Child (name) {
Father.call(this, name)}
Child.prototype = new Father()// 4. 寄生继承function cloneObj (o) {
var clone = object.create(o)
clone.sayName = ...
return clone}// 5. 寄生组合继承// 6. ES6 class extend继承
9. http状态码
• 1**: 服务器收到请求, 需请求者进一步操作
• 2**: 请求成功
• 3**: 重定向, 资源被转移到其他URL了
• 4**: 客户端错误, 请求语法错误或没有找到相应资源
• 5**: 服务端错误, server error
• 304: Not Modified. 指定日期后未修改, 不返回资源
10. Object.create实现(原型式继承,特点:实例的proto指向构造函数本身)
11. async和await:(ES8)
• Generator函数的语法糖,将*改成async,将yield换成await。
• 是对Generator函数的改进, 返回promise。
• 异步写法同步化,遇到await先返回,执行完异步再执行接下来的.
• 内置执行器, 无需next()
12. 算法和数据结构:
• 算法:
解决具体问题所需要的解决方法。执行效率最快的最优算法。时间复杂度。输入,输出,有穷性,确定性,可行性。冒泡排序,二叉树遍历,最长回文,二分查找,指针,链表等,堆栈,队列等。力扣,codewar,算法导论。
• 数据结构:
逻辑结构:集合、线性、树形、图形结构
物理结构:顺序、链式存储结构
13. 封装JSONP
jsonp
function jsonp ({url, param, callback}) {
return new Promise((resolve, reject) => {
var script = document.createElement('script')
window.callback = function (data) {
resolve(data)
document.body.removeChild('script')
}
var param = {...param, callback}
var arr = []
for (let key in param) {
arr.push(`${key}=${param[key]}`)
}
script.src = `${url}?${arr.join('&')}`
document.body.appendChild(script)
})}
14. 手动实现map(forEach以及filter也类似)
// for循环实现Array.prototype.myMap = function () {
var arr = this
var [fn, thisValue] = Array.prototype.slice.call(arguments)
var result = []
for (var i = 0; i < arr.length; i++) {
result.push(fn.call(thisValue, arr[i], i, arr))
}
return result}var arr0 = [1, 2, 3]
console.log(arr0.myMap(v => v + 1))
// forEach实现(reduce类似)Array.prototype.myMap = function (fn, thisValue) {
var result = []
this.forEach((v, i, arr) => {
result.push(fn.call(thisValue, v, i, arr))
})
return result}var arr0 = [1, 2, 3]
console.log(arr0.myMap(v => v + 1))
15. js实现checkbox全选以及反选
<body>
<button id="other">反选</button>
<input type="checkbox" id="all" />全选
<input type="checkbox" class="check" />1
<input type="checkbox" class="check" />2
<input type="checkbox" class="check" />3
<script>
var checkbox = document.getElementsByClassName('check')
var checkAll = document.getElementById('all')
var checkOther = document.getElementById('other')
checkAll.onclick = function() {
var flag = true
for (var i = 0; i < checkbox.length; i++) {
if (!checkbox[i].checked) flag = false
}
if (flag) {
for (var i = 0; i < checkbox.length; i++) {
checkbox[i].checked = false
}
} else {
for (var i = 0; i < checkbox.length; i++) {
checkbox[i].checked = true
}
}
}
checkOther.onclick = function() {
for (var i = 0; i < checkbox.length; i++) {
checkbox[i].checked = !checkbox[i].checked
}
}
</script>
</body>
16. 对原型链的理解?prototype上都有哪些属性
• 在js里,继承机制是原型继承。继承的起点是 对象的原型(Object prototype)。
• 一切皆为对象,只要是对象,就会有 proto 属性,该属性存储了指向其构造的指针。
• Object prototype也是对象,其 proto 指向null。
• 对象分为两种:函数对象和普通对象,只有函数对象拥有『原型』对象(prototype)。
• prototype的本质是普通对象。
• Function prototype比较特殊,是没有prototype的函数对象。
• new操作得到的对象是普通对象。
• 当调取一个对象的属性时,会先在本身查找,若无,就根据 proto 找到构造原型,若无,继续往上找。最后会到达顶层Object prototype,它的 proto 指向null,均无结果则返回undefined,结束。
• 由 proto 串起的路径就是『原型链』。
• 通过prototype可以给所有子类共享属性
• 函数(Function)才有prototype属性,对象(除Object)拥有proto
• 实例的proto等于构造函数的prototype
• 实例的constructor指向构造函数
17. 为什么使用继承
通常在一般的项目里不需要,因为应用简单,但你要用纯js做一些复杂的工具或框架系统就要用到了,比如webgis、或者js框架如jquery、ext什么的,不然一个几千行代码的框架不用继承得写几万行,甚至还无法维护
18. setTimeout时间延迟为何不准
单线程, 先执行同步主线程, 再执行异步任务队列
19. 事件循环述,宏任务和微任务有什么区别?
• 先主线程后异步任务队列
• 先微任务再宏任务
20. let const var作用域
块级作用域, 暂时性死区
21. 节流和防抖
• 函数节流是指一定时间内js方法只跑一次。比如人的眨眼睛,就是一定时间内眨一次。这是函数节流最形象的解释。
// 函数节流 滚动条滚动var canRun = true;
document.getElementById("throttle").onscroll = function(){
if(!canRun){
// 判断是否已空闲,如果在执行中,则直接return
return;
}
canRun = false;
setTimeout(function(){
console.log("函数节流");
canRun = true;
}, 300);};
• 函数防抖是指频繁触发的情况下,只有足够的空闲时间,才执行代码一次。比如生活中的坐公交,就是一定时间内,如果有人陆续刷卡上车,司机就不会开车。只有别人没刷卡了,司机才开车。
// 函数防抖var timer = false;
document.getElementById("debounce").onscroll = function(){
clearTimeout(timer); // 清除未执行的代码,重置回初始化状态
timer = setTimeout(function(){
console.log("函数防抖");
}, 300);};
22. 实现一个sleep函数
// 这种实现方式是利用一个伪死循环阻塞主线程。因为JS是单线程的。所以通过这种方式可以实现真正意义上的sleep()。function sleep(delay) {
var start = (new Date()).getTime();
while ((new Date()).getTime() - start < delay) {
continue;
}}
function test() {
console.log('111');
sleep(2000);
console.log('222');}
test()
23. 闭包
• 概念: 内层函数能够访问外层函数作用域的变量
• 缺点: 引起内存泄漏(释放内存)
• 作用:
o 保护this指向
o 使用闭包修正打印值
o 实现柯里化
o 实现node commonJs 模块化, 实现私有变量
o 保持变量与函数活性, 可延迟回收和执行
24. Immutable.js
Facebook出品, 倡导数据的不可变性, 用的最多就是List和Map.
25. js实现instanceof
// 检测l的原型链(__proto__)上是否有r.prototype,若有返回true,否则falsefunction myInstanceof (l, r) {
var R = r.prototype
while (l.__proto__) {
if (l.__proto__ === R) return true
}
return false}
27. ES6的模块引入和CommonJs区别
28. 严格模式
// 严格模式下, 隐式绑定丢失后this不会指向window, 而是指向undefined
'use strict'
var a = 2
var obj = {
a: 1,
b: function() {
// console.log(this.a)
console.log(this)
}
}
var c = obj.b
c() // undefined
30. typescript缺点
• 并不是严格意义的js的超集, 与js不完全兼容, 会报错
• 更多的限制, 是一种桎梏
• 有些js第三方库没有dts, 有问题
31. 构造函数实现原理(new操作符做了什么)
• 构造函数中没有显示的创建Object对象, 实际上后台自动创建了一个空对象
• 直接给this对象赋值属性和方法, this即指向创建的对象
• 没有return返回值, 后台自动返回了该对象
• 该对象继承构造函数的原型
// 模拟构造函数实现var Book = function(name) {
this.name = name;};
//正常用法var java = new Book(‘Master Java’);
//使用代码模拟,在非IE浏览器中测试,IE浏览器不支持var python = {};
python.__proto__ = Book.prototype;Book.call(python, 'Master Python');
32. for in 和 for of区别
• for in遍历数组会遍历到数组原型上的属性和方法, 更适合遍历对象
• forEach不支持break, continue, return等
• 使用for of可以成功遍历数组的值, 而不是索引, 不会遍历原型
• for in 可以遍历到myObject的原型方法method,如果不想遍历原型方法和属性的话,可以在循环内部判断一下,hasOwnPropery方法可以判断某属性是否是该对象的实例属性
33. JS实现并发控制:
使用消息队列以及setInterval或promise进行入队和出队
34. ajax和axios、fetch的区别
35. promise.finally实现
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
);};
36. 实现symbol
(function() {
var root = this;
var SymbolPolyfill = function Symbol(description) {
// Symbol函数前不能使用new命令
if (this instanceof SymbolPolyfill) throw new TypeError('Symbol is not a constructor')
// 参数是对象,则调用toString
var descString = description === undefined ? undefined : String(description)
var symbol = Object.create({
// 显示转为字符串
toString: function() {
return 'Symbol(' + this.description ')'
},
// 不能参与运算
valueOf: function() {
throw new Error('Cannot convert a Symbol value')
}
})
// 作为对象键名时,生成一个独一无二名称
// ES2019新增
symbol.prototype.description = descString
// 返回一个新对象 由于指针不同 所以两两不等
return symbol;
}
root.SymbolPolyfill = SymbolPolyfill;})();
Object.create()创建对象
37. ES6装饰器
• 提案经过大幅修改,没有定案,可能会变
• 是一种函数,用于改变类或方法的功能,起到注释作用
• 函数:
@decoratorclass A {}
// 等同于
class A {}
A = decorator(A) || A;
• 方法:
function readonly(target, name, descriptor){
// descriptor对象原来的值如下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
descriptor.writable = false;
return descriptor;}
readonly(Person.prototype, 'name', descriptor);// 类似于
Object.defineProperty(Person.prototype, 'name', descriptor);
• 先从外到内进入,经过 reverse 倒序后,然后由内向外执行。
38. 实现fetch abort
const controller = new AbortController()setTimeout(() => controller.abort(), 1000);
fetch(url, {
signal: controller.signal}).then(res => {
... }, err => {
console.log(err) // AbortError})
39. 使用xhr实现fetch
• fetch是ajax替代品,基于promise。
• 类似于jquey ajax,但不是ajax封装,而是原生js,,没有使用XHR对象
• 比ajax方便,但仍然不完善,建议使用axios库
• fetch有而axios没有的问题:
o 兼容性问题
o 默认不带cookie,需要手动设置credentials
o 跨域问题,需要手动设置mode
o 返回400、500不识别为reject
o 无法abort和timeout
• 用XHR实现fetch:
// 先实现ajaxfunction ajax(method,url,data,suc,fail) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(xhr.status == 200){
suc(xhr.responseText)
} else {
console.log(err);
fail(xhr.responseText);
}
}
};
xhr.send(data);}
// 再实现promisefunction promise () {
this.msg = '' // 存放value和error
this.status = 'pending'
var that = this
var process = arguments[0]
process (function () {
that.status = 'fulfilled'
that.msg = arguments[0]
}, function () {
that.status = 'rejected'
that.msg = arguments[0]
})
return this}
promise.prototype.then = function () {
if (this.status === 'fulfilled') {
arguments[0](this.msg)
} else if (this.status === 'rejected' && arguments[1]) {
arguments[1](this.msg)
}}
// 最后实现fetchfunction fetch(method, url, data) {
return new promise(functio