您的位置:首页 > Web前端

前端试题集合

2019-07-16 14:47 190 查看

引用作者:
https://juejin.im/post/5b03e79951882542891913e8
金三银四魔都两年半前端面经
浅谈js防抖和节流

css html篇

1、元素水平垂直居中

A元素垂直居中
A元素距离屏幕左右各边各10px
A元素里的文字font—size:20px,水平垂直居中
A元素的高度始终是A元素宽度的50%

<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
.box{
display: relative;
}
.content{
width: calc(100vw - 20px);
height: calc(50vw - 10px);
border:1px solid red;
font-size: 20px;
position: absolute;
top: 50%;
margin-top: calc(5px - 25vw);
margin-left: 10px;
// 元素水平垂直居中 方法一:
line-height: calc(50vw - 10px);
text-align: center;
// 元素水平垂直居中 方法二:
display: flex;
align-items: center;
justify-content: center;
}
</style>
-------------------------------------------------------
<div class="box">
<div class="content">111</div>
</div>

2、事件循环和回调队列

微任务:promise
宏任务:setTimeout
async执行之后,遇到await先返回(async返回promise对象),再走promise的方法,再走async里的的代码,再走promise then里的代码,最后是setTimeout(await返回promise对象的处理结果,也就是then)

async function async1(){
console.log(‘async1 start’)
await async2()
console.log(‘async1 end’)
}
async function async2(){
console.log(‘async2’)
}
console.log(‘script start’)
setTimeout(function(){
console.log(‘setTimeout’)
},0)
async1();
new promise(function(resolve){
console.log(‘promise1’)
resolve();
}).then(function(){
console.log(‘promise2’)
})
console.log(‘script end’)

3、手写bind方法
Function.prototype.my_bind = function() {
var self = this, // 保存原函数
// 保存需要绑定的this上下文
context = Array.prototype.shift.call(arguments),
// 上一行等价于 context = [].shift.call(arguments);
// 剩余的参数转为数组
args =
3ff7
Array.prototype.slice.call(arguments);
// 返回一个新函数
return function() {
// 这里的arguments是9
self.apply(context, Array.prototype.concat.call(args, Array.prototype.slice.call(arguments)));
}
}

function a(m, n, o) {
console.log(this.name + ' ' + m + ' ' + n + ' ' + o);
}

var b = {
name: 'kong'
};

a.my_bind(b, 7, 8)(9); // kong 7 8 9
4、URL从输入到页面渲染全流程

DNS域名解析
TCP连接
HTTP请求
处理请求返回HTTP响应
页面渲染
关闭连接

5、JS防抖与节流

窗口resize、scroll时,如果不加以控制,调用频率太高

防抖(debounce)

设置一个时间节点2s;在2s内,没触发事件,则执行代码;2s内,触发事件,则清除计时,重新开始2s计时。

function debounce(fn,delay){
let timer = null //借助闭包
return function() {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(fn,delay) // 简化写法
}
}

function resizeHandle() {
console.log(document.body.clientWidth)
}

window.onresize = throttle(resizeHandle, 1000)
节流(throttle)

设置一个时间节点2s,在2s内,无论是否再次触发事件,都在2s后执行代码

function throttle(fn,delay){
let valid = true
return function() {
if(!valid){
//休息时间 暂不接客
return false
}
// 工作时间,执行函数并且在间隔期内把状态位设为无效
valid = false
setTimeout(() => {
fn()
valid = true;
}, delay)
}
}
6、[“1”, “2”, “3”].map(parseInt)输出结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: