面试题

172 阅读1分钟

用setTimeout实现setInterval

function mySetInterval(fn, gap){
	function Interval(){
    	setTimeout(Interval, gap)
        fn()
    }
    setTimeout(Interval, gap)
}

实现promise.all

Promise.prototype._all = function(promises){
	return new Promise((resolve, reject) => {
    	if(!Array.isArray(promises)){
    		throw new TypeError('promises must be an array')
    	}
    	let res = []
        promises.forEach((promise, index) => {
        	promise.then(p => {
            	res.push(p)
                if(res.length === promises.length) {
            		resolve(res)
            	}
            }, err => {
            	reject(err)
            })
        })
    })
}

实现axios中的get和post

vue中的scope原理

代码题

const tree = {
    value: 1,
    children:[
        { 
            value: 3,
            children: [
                {
                	value: 4
                }
            ]
       }
   ]
}

// 3 [1,3]
// 4 [1,3,4]

function findPath(obj, target){
	let res = []
    return _findPath(obj, res, target)
}

function _findPath(obj, res, target){
	if(!obj){
    	return false
  	}
    
    if(obj.value === target){
    	res.unshift(obj.value)
    	return true
  	} else {
    	for(let item of obj.children){
      		if(findPath(item, res, target)){
        		res.unshift(obj.value)
        		return true
      		}
    	}
  	}
}

promise、async、await

https://segmentfault.com/a/1190000016788484
https://segmentfault.com/a/1190000015057278?utm_source=tag-newest