1.判断数据类型
利用object 原型上的 toString方法判断数据类型
let toSting = Object.prototype.toSting;
toString.call("134") // "[object String]"
toSting.call(123) // "[object String]"
toString.call({}) // "[object Object]"
toSting.call(function(){}) //"[object Function]"
toString.call(true) // "[object Boolean]"
toString.call(undefined); //"[object Undefined]"
toString.call(null); //"[object Null]"
toString.call(new Date()); //"[object Date]"
toString.call(/^[a-zA-Z]{5,20}$/); //"[object RegExp]"
toString.call(new Error()); //"[object Error]"
2.防抖函数
@ 参数type为1时:时间戳版
@ 参数type为2时:定时器版
function throttle(func, wait ,type) {
if(type===1){
let previous = 0;
}else if(type===2){
let timeout;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
_________________________________________________________________________________________________________
@@@@@@@@@@@@@@ 又或者
function debounce(fn,wait){
var td;
return function(){
clearTimeout(td);
td= setTimeout(fn,wait);
}
}
调用:
let myFunc =debounce(function (){
// 执行你的代码
},250)
window.addEventListener('resize',myFunc);
3.函数柯里化(经典面试题)
// 实现一个add方法,使计算结果能够满足如下预期:
add(1)(2)(3) = 6;
add(1, 2, 3)(4) = 10;
add(1)(2)(3)(4)(5) = 15;
function add() {
// 第一次执行时,定义一个数组专门用来存储所有的参数
var _args = Array.prototype.slice.call(arguments);
// 在内部声明一个函数,利用闭包的特性保存_args并收集所有的参数值
var _adder = function() {
_args.push(...arguments);
return _adder;
};
// 利用toString隐式转换的特性,当最后执行时隐式转换,并计算最终的值返回
_adder.toString = function () {
return _args.reduce(function (a, b) {
return a + b;
});
}
return _adder;
}
add(1)(2)(3) // 6
add(1, 2, 3)(4) // 10
add(1)(2)(3)(4)(5) // 15
add(2, 6)(1) // 9