【问题标题】:Javascript interview question (mul functions)Javascript面试题(mul函数)
【发布时间】:2020-09-29 09:20:59
【问题描述】:

知道这是如何工作的吗?

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 函数中给出索引是如何工作的

【问题讨论】:

  • 很抱歉,我不明白这个问题。为什么它不能那样工作?第二级函数返回一个数组,数组元素可以通过索引访问。仅此而已。
  • 你是什么意思?

标签: javascript indexing


【解决方案1】:

在 javascript 中,一个函数可以是另一个函数的返回值。 在这种情况下,mul 正在返回一个函数,该函数返回一个数组。数组的第一个元素是 x*y,第二个元素是函数。

mul(2); // Returns a function which can take one argument
mul(2)(3) // Invoking the function returned from mul using 3 as argument, this will return the array

mul(2)(3)[0]; // Accessing the first element of the array - 6
mul(2)(3)[1](4); /** With mul(2)(3)[1] we are accessing the second element of the array, 
                  since it is a function taking one argument we can pass 4 as argument to it
                 **/

【讨论】:

    【解决方案2】:

    罗比是正确的。扩展他的解释......第一个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。

    【讨论】:

      【解决方案3】:

      嵌套函数有点难理解,但是当你想等待某个值时通常会使用它们。

      例如,假设在这种情况下我没有 z

      function sum(y, z) {
          return y + z;
      }
      

      所以我可以清楚地使用嵌套函数,所以我可以像这样等待 z:

      function sum(y) {
          return function(z) {
              return y + z;
          }
      }
      
      const temporaryValue = sum(10); // it returns another function;
      
      const result = temporaryValue(5); // here, i have the function result
      

      你的代码在做什么,基本上就是它!但它使用的是数组。我会尽力为你解释。

      function mul(x){
          return function(y) { // returns another function
              // that returns an array, with another function inside it
              return [x * y, function(z) {
                  return x * y + z; // that returns it's result;
              }];
          }
      }
      
      const temporaryAgain = mul(2); // returns a function
      const nearThere = temporaryAgain(3); // returns an array
      const result = nearThere[1](4); // [1] returns a function and (4) returns the result
      

      这正是您发送的代码的作用!!希望我能有所帮助。 如果没有,我强烈建议你学习一下nested functions

      【讨论】:

        猜你喜欢
        • 2017-04-15
        • 2011-03-04
        • 1970-01-01
        • 2021-11-12
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多