1,下面代码的执行顺序是什么?
onsole. log ( 1 ) ;
setTimeout ( ( ) => {
console. log ( 2 )
Promise. resolve ( ) . then ( ( ) => {
console. log ( 3 )
} )
setTimeout ( ( ) => {
console. log ( 4 )
} , 0 )
} , 0 )
new Promise ( ( resolve, reject ) => {
console. log ( 5 )
resolve ( 6 )
} ) . then ( ( data ) => {
console. log ( data)
data = 7
} ) . then ( ( data ) => {
console. log ( '!!!' + data)
} )
setTimeout ( ( ) => {
console. log ( 8 )
} , 0 )
console. log ( 9 )
2,手写一个数组的 reduce 方法
Array . prototype. myReduce = function myReduce ( fn, base ) {
if ( typeof fn !== "function" ) {
throw new TypeError ( "arguments[0] is not a function" ) ;
}
let initialArr = this ;
let arr = initialArr. concat ( ) ;
if ( base) arr. unshift ( base) ;
let index, newValue;
while ( arr. length > 1 ) {
index = initialArr. length - arr. length + 1 ;
newValue = fn . call ( null , arr[ 0 ] , arr[ 1 ] , index, initialArr) ;
arr. splice ( 0 , 2 , newValue) ;
}
return newValue;
} ;
3,手写debounce函数,debounce是防抖的意思
const debounce = debounce ( fn, wait ) {
let timer = null
return function ( ) {
if ( timer) {
clearTimeout ( timer)
}
timer = setTimeout ( ( ) => {
fn ( ) ;
timer = null ;
} , wait)
}
}
const throttle = throttle ( func : Function, delay : number) {
let timer : Object | null = null
return function ( ) {
if ( ! timer) {
timer = setTimeout ( ( ) => {
func ( )
timer = null
} , delay)
}
}
}
4,var arr = [0, [1, 3],[2, 5], 4] 降维度
function flatten ( arr ) {
var res = [ ] ;
arr. map ( item => {
if ( Array. isArray ( item) ) {
res = res. concat ( flatten ( item) ) ;
} else {
res. push ( item) ;
}
} ) ;
return res;
}
5,使用ajax发送一个请求,在两秒内未响应则取消该请求
let xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , '/api' , false ) ;
xhr. send ( ) ;
setTimeout ( ( ) => {
xhr. abort ( ) ;
} , 2000 )
const CancelToken = axios. CancelToken;
const source = CancelToken. source ( ) ;
axios. get ( '/user/12345' , {
cancelToken : source. token
} ) . catch ( function ( thrown ) {
if ( axios. isCancel ( thrown) ) {
console. log ( 'Request canceled' , thrown. message) ;
} else {
}
} ) ;
axios. post ( '/user/12345' , {
name : 'new name'
} , {
cancelToken : source. token
} )
source. cancel ( 'Operation canceled by the user.' ) ;