一道字节的闭包面试题
昨天在b站上看到一个字节面试题的视频,看的我一脸懵,自己写了一下,发现被up绕进去了,明明是个简单题。下面记录下解题思路,若有问题欢迎评论指正。
题目如下
js
// 编写一个函数,实现下面的输出
function foo(...args) {}
const f1 = foo(1, 2, 3)
console.log(f1.getValue()) // 6
const f2 = foo(1, 2)(3)
console.log(f2.getValue()) // 6
const f3 = foo(1)(2, 3)(4)
console.log(f3.getValue()) // 10
思路
1.这个函数会返回一个函数,能够链式调用
2.在这个函数里面肯定有一个变量形成闭包来存储链上的所有参数
代码实现
js
// 编写一个函数,实现下面的输出
function foo(...args) {
// 存储的数组
const cacheArr = [...args]
// 创建一个函数,使他能够返回自身,并且保持cache的作用域链
const fn = (...args2) => {
cacheArr.push(...args2)
return fn
}
// 给fn增加getValue方法
fn.getValue = () => {
return cacheArr.reduce((pre, val) => pre + val)
}
return fn
}
const f1 = foo(1, 2, 3)
console.log(f1.getValue())
const f2 = foo(1, 2)(3)
console.log(f2.getValue())
const f3 = foo(1)(2, 3)(4)
console.log(f3.getValue())
// 控制台输出 6 6 10