首页 > 解决方案 > Javascript面试题(mul函数)

问题描述

知道这是如何工作的吗?

function mul(x) {
    return function(y) {
	return [x*y, function(z) {
	    return x*y + z;
	}];
    }
}

console.log(mul(2)(3)[0]);
console.log(mul(2)(3)[1](4));

我不确定在 mul 函数中给出索引是如何工作的

标签: javascriptindexing

解决方案


罗比是正确的。扩展他的解释......第一个console.log;

console.log(mul(2)(3)[0]);

正在返回调用前两个函数后返回的数组的索引 0... x*y,即 2*3 = 6。第二个 console.log;

console.log(mul(2)(3)[1](4));

在该点返回索引 1,它返回将 z 作为参数的函数......一旦将 z 传递给函数,它返回 x*y + z,即 2*3 + 4 = 10。


推荐阅读