测试例子一
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<script>
function sum() {
var total = 0;
var args = Array.prototype.slice.call(arguments);
var add = function (num) {
total += num;
return add;
};
add.toString = function () {
return `${total}`;
}
add.get = function () {
return total;
}
args.forEach(element => {
total += element;
});
return add;
}
console.log(sum(1)(2)(3));
console.log(sum(1, 2, 3)); //6
console.log(sum(1, 2, 3, 4, 5, 6)); //21
console.log(sum(1)(2)(3)(4)(5)(6)); //21
console.log(sum(1, 2)(3)(4)(5)(6)); //21
</script>
</body>
</html>
测试例子二
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函数柯理化运用</title>
</head>
<body>
<script>
console.log(add(1)(2)(3)(4));
console.log(add(1, 2, 3, 4));
console.log(add(1, 2)(3, 4));
console.log(add(1, 2, 3)(4));
function add() {
var args = Array.prototype.slice.call(arguments);//伪数组转数组
function hardAdd() {
var innerArgs = Array.prototype.slice.call(arguments, 0);//伪数组转数组
args = args.concat(innerArgs);//合并参数
return hardAdd;
}
hardAdd.toString = function () {//重写toString方法
return args.reduce((previous, current) => {//用reduce做累加
return previous + current
});
}
return hardAdd;
}
</script>
</body>
</html>
代码分析
1.sum(x)(y)(z)...要能够调用,该函数返回值必须是一个function类型
2.sum(x,y,z,..)也能调用,则该函数能够处理多参数且多参数
3.要求控制台能够打印那么久需要重写参数为1是返回函数的toString方法。否在打印结果为该函数的源码
5.为了方便打印,这里直接写了一个get方法用户获取求和的结果
要点
1.js函数arguments的用法
2.js闭包的用法
3.函数柯理化
网友评论