• 前端最全手写面试题


    防抖函数

    function dou(fn,s){
    	let _=''
    	return function(...arg){
    		clearTimeout(_)
    		_=setTimeout(()=>{
    			fn.apply(this,arg)
    		},s)
    	}
    }
    

    节流函数

    function dou(fn,s){
    	let _=''
    	return function(...arg){
    		if(!_)return
    		_=false
    		setTimeout(()=>{
    			_=true
    			fn.apply(this,arg)
    		},s)
    	}
    }
    

    手写Object.create

    function _create(obj) {
    	function C() {}
    	C.prototype = obj;
    	return new C();
    }
    

    睡眠函数

    function sleep(s){
    	return new Promise(resolve=>{
    		setTimeout(resolve,s)
    	})
    }
    
    运行
    sleep(1000).then(()=>alert(1))
                或
    !async function run() {
    	await sleep(1500);
    	console.log('start await');
    }()
    

    js进行浮点运算

    function float_() {
    	let cc = Array.from(arguments)
    	let cc_ = cc.map(i => {
    		let _ = String(i).split('.')[1]
    		return _ ? _ : 0
    	})
    	let len = Math.max(...cc_)
    	return cc.reduce((sum , i) => sum + i ### 10 ###* len, 0) / 10 ###* len
    }
    

    手写ajax

    function ajax(obj){
    	let _=Object.assign({
    		methods:'GET',
    		url:'www.xxx.com',
    		data:''
    	},obj)
    	return new Promise((resolve,reject)=>{
    		let xhr = new XMLHttpRequest,
    			sendData = ''
    		if(_.data){
    			for(let i in _.data){
    				sendData += `&${i}=${_.data[i]}`
    			}
    		}
    		let url = sendData ? `${obj.url}?${sendData}` : obj.url
    		if (methods = 'GET') {
    			xhr.open('GET', url, true)
    			xhr.send(sendData)
    		}
    		if (methods = 'POST') {
    			xhr.open('POST', obj.url, true)
    			xhr.send(sendData.slice(1))
    		}
    		xhr.onreadystatechange = function() {
    			if (xhr.readyState == 4) {
    				if (xhr.status == 200 || XHR.status === 304) {
    					resolve(JSON.parse(xhr.responseText))
    				} else {
    					reject(Error)
    				}
    			}
    		}
    	})
    }
    

    队列函数(无论是否异步按照顺序调用函数)

    let stack=[],
        index=0
    function next(){
    	var fn=stack[i]
    	index += 1 
    	if (typeof fn == 'function') {
    		fn();
    	}
    }	
    function fn1(){
    	console.log('第一个调用')
    	next();
    }
    function fn2(){
    	setTimeout(function() {
    		console.log('第二个被调用');
    		next();
    	}, 1000)
    }
    function fn3() {
    	console.log('第三个调用');
    	next();
    }
    stack.push(fn1, fn2, fn3)
    next();
    

    使用async写异步函数(图片是否被正确加载)

    async function load(url) {
    	var image = new Image();
    	image.onload = function() { //图片加载成功,调用resolve方法
    		return console.log(image)
    	};
    	image.onerror = function() { //图片加载不成功,调用reject方法
    		throw '错误'
    	};
    	image.src = url;
    }
    运行
    ~async function img() {
    	return await load(
    		'https://www.xxx.com'
    	)
    }()
    

    Instanceof函数

    function Instanceof_(obj, fn) {
    	while (true) {
    		if (obj.__proto__ === null) return false
    		if (obj.__proto__ === fn.prototype) return true
    		 obj= obj.__proto__;
    	}
    }
    

    call函数

    Function.prototype.call_ = function() {
    	let obj = Array.from(arguments)[0] || window,
    		arg = Array.from(arguments).slice(1),
    		key = Symbol(),
    		result
    	obj[key] = this
    	result = obj[key](...arg)
    	delete obj[key]
    	return result
    }
    

    bind函数

    Function.prototype.bind_ = function() {
    	let obj = Array.from(arguments)[0] || window,
    		arg = Array.from(arguments).slice(1),
    		self = this
    	return function(){
    		let args=Array.from(arguments).slice(1)
    		return self.call(obj,[...arg,...args])
    	}
    }
    

    EventEmitter(收集发布)

    class EventEmitter {
    	constructor() {
    		this.obj = {}
    	}
    	on(key, fn) {
    		let Events = []
    		Event.push(fn)
    		this.obj[key] = Event
    	}
    	emit(key, ...arg) {
    		let Events = this.obj[key]
    		if (Events) {
    			Events.forEach(i => i(...arg))
    		}
    	}
    }
    

    dom节点的遍历

    function one_(node) {
    	if (node.nodeType == 1) {
    		console.log(node.tagName.toLowerCase())
    	}
    	for (var i = 0; i < node.childNodes.length; i++) {
    		if (node.childNodes[i].nodeType === 1) {
    			one_(node.childNodes[i])
    		}
    	}
    }
    

    LRU算法

    class LRUCache {
    	constructor(capacity, intervalTime) {
    		this.cache = new Map();
    		this.capacity = capacity; //最大容量
    		this.intervalTime = intervalTime; //过期时间
    	}
    	get(key) {
    		if (!this.cache.has(key)) {
    			return null
    		} //查不到对应的k-value
    		const tempValue = this.cache.get(key)
    		this.cache.delete(key);
    		if (Date.now() - tempValue.time > this.intervalTime) {
    			return null
    		}
    		this.cache.set(key, {
    			value: tempValue.value,
    			time: Date.now()
    		})
    		return tempValue.value
    	}
    	put(key, value) {
    		if (this.cache.has(key)) {
    			this.cache.delete(key)
    		}
    		if (this.cache.size >= capacity) { //满了
    			const keys = this.cache.keys()
    			this.cache.delete(keys.next().value)
    		}
    		this.cache.set(key, {
    			value,
    			time: Date.now()
    		})
    	}
    }
    

    es5继承

    function Far(name){
            this.name = name;
            this.color = ["red","green","blue"];
        }
        Far.prototype.sayName = function(){
            console.log(this.name);
        };
    function Son(name,age){
            Far.call(this,name);
            this.age  = age;
        }
    	Son.prototype=Object.creat(Far.prototype)
    	San.prototype.constructor = San
    

    es6继承

    class Far {
    	constructor(props) {
    	this.name = props.name
    	}
    	sayName() {
    		console.log(this.name);
    	}
    }
    class Son extends Far {
    	constructor(props,myAttribute) {//props是继承过来的属性,myAttribute是自己的属性
    	super(props)//相当于获得父类的this指向
    	this.name = name
    	}
    }
    

    手写new

    function new_(fn,arg){
    	let obj={}
    	Object.Object.getPrototypeOf(obj,fn.prototype)
    	fn.apply(obj,arg)
    	return obj
    }
    

    手写Promise

    function Promise_(test_) {
    	let self = this
    	this.status = 'padding'
    	this.value = ''
    	this.reason = ''
    	this.resolveArr = []
    	this.rejectArr = []
    
    	function resolve(value) {
    		if (self.status == 'padding') {
    			self.value = value
    			self.status = 'resolved'
    			self.resolveArr.forEach(i => i())
    		}
    	}
    
    	function reject(reason) {
    		if (self.status == 'padding') {
    			self.value = reason
    			self.status = 'rejected'
    			self.rejectArr.forEach(i => i())
    		}
    	}
    	try {
    		test_(resolve, reject)
    	} catch (e) {
    		reject(e)
    	}
    }
    Promise_.prototype.then = function(onResolve, onReject) {
    	if (this.status == 'rejected') {
    		onReject(this.reason)
    	}
    	if (this.status == 'resolved') {
    		onResolve(this.value)
    	}
    	if (this.status == 'padding') {
    		this.resolveArr.push(() => {
    			onResolve(this.value)
    		})
    		this.rejectArr.push(() => {
    			onReject(this.reason)
    		})
    	}
    }
    

    手写reduce

    Array.prototype.reduce_2 = function(fn, back = 0) {
    	let arr = this
    	for (var i; i < arr.length; i++) {
    		return !back ? fn(arr[i], arr[i + 1], i + 1, arr) : fn(back, arr[i], i, arr)
    	}
    }
    

    手写map

    Array.prototype.map_ = function(fn) {
    	let arr = this
    	let arr_ = []
    	for (let i = 0; i < arr.length; i++) {
    		arr_[i] = fn(arr[i], i, arr)
    	}
    	return arr_
    }
    

    手写filter

    Array.prototype.filter_=function(fn){
    	let arr=this,
    	arr_=[]
    	for (let i = 0; i < arr.length; i++) {
    		if(fn(arr[i],i,arr)){
    			arr_[i]=arr[i]
    		}
    	}
    	return arr_
    }
    

    实现二分搜索法

    function Search_(value, arr, startIndex, endIndex) {
    	var len = arr.length,
    		startIndex = typeof startIndex === "number" ? startIndex : 0, //开始的数
    		endIndex = typeof endIndex === "number" ? endIndex : len - 1, //结束的数
    		midIndex = Math.floor((startIndex + endIndex) / 2), //中间的数
    		midval = arr[midIndex]; 
    
    	if (midval === value) {
    		return midIndex;
    	} else if (midval > value) {
    		return Search_(value, arr, startIndex, midIndex - 1);
    	} else {
    		return Search_(value, arr, midIndex + 1, endIndex);
    	}
    }
    

    实现冒泡排序

    function bubbing_(arr) {
    	for (let i = 0; i < arr.length - 1; i++) {
    		for (let j = 0; j < arr.length - 1 - i; j++) {
    			if (arr[j] > arr[j + 1]) {
    				[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
    			}
    		}
    	}
    	return arr
    }
    

    实现选择排序

    function select_(arr) {
    	for (let i = 0; i < arr.length; i++) {
    		for (let j = i + 1; j < arr.length; j++) {
    			if (arr[j] < arr[i]) {
    				[arr[j], arr[i]] = [arr[i], arr[j]]
    			}
    		}
    	}
    	return arr
    }
    

    实现插入排序

    function insert(array) {
    	for (let i = 1; i < array.length; i++) { 
    		var j = i - 1; 
    		while (j >= 0 && array[j] > array[i]) { 
    			[arr[j], arr[i]] = [arr[i], arr[j]] 
    			j--;
    		}
    	}
    	return array;
    }
    

    实现快速排序

    function fast_(arr) {
    	let len = arr.length,
    		r = [],
    		l = [],
    		bsc = arr[0]
    	if (len < 2) {
    		return arr
    	}
    	for (let i = 1; i < len; i++) {
    		if (arr[i] < bsc) {
    			l.push(arr[i])
    		} else {
    			r.push(arr[i])
    		}
    	}
    	return [...k(l), bsc, ...k(r)]
    }
    

    取任意区间任意个任意值

    function yi(mi, ma, k) {
    	if (mi > ma)[mi, ma] = [ma, mi]
    	let max = Math.floor(ma),
    		min = Math.ceil(mi),
    		o = new Set()
    	while (o.size < k) {
    		o.add(Math.floor(Math.random() * (max - min + 1)) + min)
    	}
    	let c = [...o].sort((a, b) => {
    		return a - b
    	}) 
    	let _c = c.reduce((a, b) => a + b, 0)
    	return _c
    }
    
  • 相关阅读:
    Introduce myself
    二叉搜索树的后序遍历序列(剑指offer-23)
    从上到下打印二叉树(剑指offer-22)
    二叉树的深度(剑指offer-38)
    不用加减乘除做加法(剑指offer-48)
    栈的压入、弹出序列(剑指offer-21)
    Java容器
    包含min函数的栈(剑指offer-20)
    在Docker中创建Mongodb数据库
    词向量聚类实验
  • 原文地址:https://www.cnblogs.com/GET-one/p/12628771.html
Copyright © 2020-2023  润新知