什么叫函数柯里化?其实就是将使用多个参数的函数转换成一系列使用一个参数的函数的技术。还不懂?来举个例子
function add(a, b, c) {
return a + b + c
}
add(1, 2, 3)
let addCurry = curry(add)
addCurry(1)(2)(3)
现在就是要实现 curry 这个函数,使函数从一次调用传入多个参数变成多次调用每次传一个参数。
// fn.length 会返回 函数的参数个数
// 如果 addCurry调用时传入的参数为3, 与add函数的形成个数一样,那么直接执行add函数
// 如果 不一样,那么再返回一个函数,并且把当前参数作为返回函数的形参,并等待 返回参数传参
function curry(fn) {
let judge = (...args) => {
if (args.length == fn.length) return fn(...args)
return (...arg) => judge(...args, ...arg)
}
return judge
}
一道经典面试题
// 实现一个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
BFC
BFC(Block formatting context)直译为"块级格式化上下文"。它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,并且与这个区域外部毫不相干。
现象
如果一个盒子,内部元素都浮动,盒子没有设置height的前提下,无法撑起自身,那么这个盒子没有形成BFC
创建BFC的方法
- float不是none
- position 不是relative或者 static
- display的值是 inline-block、flex、inline-flex
- overflow: hidden (推荐这种)
可以解决的问题
- 解决margin塌陷问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
font-size: 0;
}
.father {
width: 200px;
height: 200px;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
background-color: aqua;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>

结果father上面出现了20px;
.father {
width: 200px;
height: 200px;
background-color: pink;
/* position: absolute; */
/* display: inline-block; */
/* float: left; */
overflow: hidden;
}

- 阻止浮动的元素遮盖其他元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
font-size: 0;
}
.son {
width: 100px;
height: 100px;
background-color: aqua;
float: left;
}
.son2 {
width: 100px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
<div class="son"></div>
<div class="son2"></div>
</div>
</body>
</html>

son2被浮动的son元素遮挡了
也与上面father的一样可以通过4中方法解决
参考:
https://juejin.cn/post/6946022649768181774?utm_campaign=sembaidu&utm_medium=sem_baidu_jj_pc_dc01&utm_source=bdpcjj00225#heading-16
https://www.jianshu.com/p/2975c25e4d71
网友评论