一道关于JavaScript柯里化的面试题 发表于 2017-02-04 | 题目123编写一个函数console.log(mul(1)(2)(3)) //6 console.log(mul(2)(3)(4)) //24 解法优解123456789101112131415161718192021222324252627282930313233// es6 const mul = (x) => { let sum = x let curried = (y) => { sum = sum * y return curried } curried.toString = () => sum return curried } console.log(mul(1)) //1 console.log(mul(1)(2))//2 console.log(mul(1)(2)(3))//6 console.log(mul(1)(2)(3)(4))//24 ... // es5 function mul(x){ var sum = x var curried = function(y){ sum = sum * y return curried } curried.toString=function(){ return sum } return curried} console.log(mul(1)) //1 console.log(mul(1)(2))//2 console.log(mul(1)(2)(3))//6 console.log(mul(1)(2)(3)(4))//24 ... 这种解法主要用的是闭包,然后将函数作为返回值,然后重写curried的toString 最简单的解法12345678910111213//es6const mul = (x) =>(y) =>(z) => x*y*zconsole.log(mul(1)(2)(3))//es5function mul(x){ return function(y){ return function(z){ return x*y*z } }}console.log(mul(1)(2)(3)) 这种解法就是完全,就是使用柯里化了