文章目录
实现一个函数去重? 实现一个函数,判断指定元素在数组中是否存在? 实现一个函数,将给定字符串反转? 实现一个函数,检测指定字符串是否为回文(即从前往后和从后往前的字符序列都相同)? 实现一个函数,计算两个数的最大公约数? 实现Array.prototype.reduce函数 实现 一个类似setTimeout的函数delay(ms) 实现一个防抖函数debounce(fn, delayTime) 实现一个节流函数throttle(fn, intervalTime) 实现一个深度拷贝函数deepClone(obj)
实现一个函数去重?
function unique ( array ) {
return Array. from ( new Set ( array) ) ;
}
实现一个函数,判断指定元素在数组中是否存在?
function includes ( array, value ) {
for ( let i = 0 , len = array. length; i < len; i++ ) {
if ( array[ i] === value) {
return true ;
}
}
return false ;
}
实现一个函数,将给定字符串反转?
function reverseString ( str ) {
const arr = str. split ( '' ) ;
arr. reverse ( ) ;
return arr. join ( '' ) ;
}
实现一个函数,检测指定字符串是否为回文(即从前往后和从后往前的字符序列都相同)?
function isPalindrome ( str ) {
return reverseString ( str) === str;
}
function reverseString ( str ) {
return str. split ( '' ) . reverse ( ) . join ( '' ) ;
}
实现一个函数,计算两个数的最大公约数?
function gcd ( num1, num2 ) {
return num2 ? gcd ( num2, num1 % num2) : num1;
}
实现Array.prototype.reduce函数
Array . prototype. myReduce = function ( fn, initialValue ) {
let accum = initialValue === undefined ? undefined : initialValue;
for ( let i = 0 ; i < this . length; i++ ) {
if ( accum !== undefined ) {
accum = fn . call ( undefined , accum, this [ i] , i, this ) ;
} else {
accum = this [ i] ;
}
}
return accum;
} ;
实现 一个类似setTimeout的函数delay(ms)
function delay ( ms ) {
return new Promise ( ( resolve ) => setTimeout ( resolve, ms) ) ;
}
实现一个防抖函数debounce(fn, delayTime)
function debounce ( fn, delayTime ) {
let timerId;
return function ( ) {
const context = this ;
const args = arguments;
clearTimeout ( timerId) ;
timerId = setTimeout ( ( ) => {
fn . apply ( context, args) ;
} , delayTime) ;
} ;
}
实现一个节流函数throttle(fn, intervalTime)
function throttle ( fn, intervalTime ) {
let timerId;
let canRun = true ;
return function ( ) {
const context = this ;
const args = arguments;
if ( ! canRun) return ;
canRun = false ;
timerId = setTimeout ( function ( ) {
fn . apply ( context, args) ;
canRun = true ;
} , intervalTime) ;
} ;
}
实现一个深度拷贝函数deepClone(obj)
function deepClone ( obj ) {
if ( typeof obj !== 'object' || obj === null ) {
return obj;
}
let result = Array. isArray ( obj) ? [ ] : { } ;
for ( let key in obj) {
if ( obj. hasOwnProperty ( key) ) {
result[ key] = deepClone ( obj[ key] ) ;
}
}
return result;
}