2018web前端面试题总结 (15)

AJAX状态码:0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send方法,正在发送请求
2 - (载入完成呢)send()方法执行完成
3 - (交互)正在解析相应内容
4 - (完成)响应内容解析完成,可以在客户端调用了


三、函数节流(throttle)
function throttle (func, wait) {
var timeout;
var previous = 0;
return function () {
context = this;
args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context,args)
}, wait);
}
}
}

}

四、函数防抖(dobounce)
function debounce (func, wait) {
var timeout;
return function() {
var context = this;
var args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context,args)
}, wait);
}
}

五、实现一个函数clone,可以对JavaScript中的5种主要的数据类型(包括Number、String、Object、Array、Boolean)进行值复制

Object.prototype.clone = function() {
var newObject = this.constructor === Array ? [] : {} //对象的深拷贝 获取对应的构造函数 [] 或者 {}
for (let e in this) { //遍历对象的属性 in this[e]
newObject[e] = typeof this[e] === 'object' ? this[e].clone() : this[e] //对象中的属性如果还是对象 那就继续递归 否则就返回基本的数据类型
}
return newObject
}

六、实现一个简单的Promise https://juejin.im/post/5b2f02cd5188252b937548ab
class Promise {
constructor (executor) { // executor里面有两个参数,一个叫resolve(成功),一个叫reject(失败)。
this.status = 'pending',
this.value = undefined;
this.reason = undefined;
// 成功存放的数组
this.onResolvedCallbacks = [];
// 失败存放法数组
this.onRejectedCallbacks = [];
let resolve = (value) => {
if (this.status == 'pending') {
this.status = 'resolve';
this.value = value;
this.onResolvedCallbacks.forEach(fn => fn())
}
}

let reject = (reason) => {
if (this.status == 'pending') {
this.status = 'reject';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn())
}
}
try{
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then (onFullFilled,onRejected) {
if (this.status == 'resolved') {
onFullFilled(this.value)
}
if (this.status == 'rejectd') {
onRejected(this.reason);
}
if (this.status == 'pending') {
this.onResolvedCallbacks.push(()=>{
onFullFilled(this.value);
})
this.onRejectedCallbacks.push(()=> {
onRejected(this.reason);
})
}

}
}

const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hello world')
}, 1000);
})
p.then((data) =>{
console.log(data)
},(err) =>{
console.log(err);
})

七、发布订阅者模式(观察者模式)

var event = {}; // 发布者
event.clientList = [] //发布者的缓存列表

event.listen = function (fn) { // 增加订阅者函数
this.clientList.push(fn)
}

event.trigger = function () { // 发布信息
for (var i =0;i<this.clientList.length;i++) {
var fn = this.clientList[i];
fn.apply(this, arguments);
}
}

event.listen (function(time) {
console.log('正式上班时间为:' +time)
})
event.trigger ('2018/7')

八、手动写一个node服务器
const http = require('http');
const fs = require('fs');
const server = http.createServer((req,res) => {
if (reu.url == 'http://www.likecs.com/') {
const indexFile = fs.createReadStream('./index.html')
req.writeHead(200,{'context-Type':'text/html;charset = utf8})
indexFile.pipe(res)
}
server.listen(8080)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyjfsg.html