<style>
#box {
width: 0;
height: 0;
border: 40px solid transparent;
border-bottom: 40px solid tomato;
}
</style>
<body>
<!-- css实现三角形 -->
<div id="box"></div>
<!-- 实现节流防抖 -->
<button id="ok">ok</button>
<script>
/* 节流 */
function throttle(func,wait){
let previous = 0 ;
return function () {
let args = arguments;
let now = Date.now();
if((now-previous) > wait) {
func.apply(this,args)
}
previous = now;
}
}
/* 防抖 */
function debounce(func,delay){
let timer;
return function(){
let args = arguments;
if(timer) clearTimeout(timer);
timer = setTimeout(function (){
func.apply(this,args)
},delay)
}
}
function showClick(str = 'click') { console.log(str) }
document.getElementById('ok').addEventListener('click',
function () {
throttle(showClick,1000)('throttle')
}
)
document.getElementById('ok').addEventListener('click',
function() {
debounce(showClick,1000)('debounce')
}
)
/* 函数柯里化 */
// 普通函数
function normalAdd(a,b){
return a + b
}
// 柯里化函数
function curryingAdd (x) {
return function (y) {
return x+y
}
}
// 经典面试题
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;
}
前端面试常见题型——节流防抖函数柯里化
最新推荐文章于 2023-05-15 17:28:23 发布