如何在闭包中乘以数字

时间:2018-05-06 16:36:16

标签: javascript

如何实现锁定函数以乘以任意数量的数字。通话示例:multiply (1) (2) (3) (4) (5) // 120。要完成此任务,有必要重新定义内部函数的toString方法,该方法应返回累积结果,但我得到结果NaN



function Multiply(arguments) {

    for(var i =0; i <arguments.length; i++) {
      var number = arguments.length[i];
    }
    return function (res) {
        return number*res.valueOf();
    };
}
console.log(Multiply(5)(5)(6)(8));
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

首先不要在函数中使用arguments作为参数,因为此变量在函数中可用作函数参数的对象(arguments object)。

然后你需要一个内部函数m,它使用参数并计算产品并返回函数本身。

内部函数获取toString方法以获取最终结果。

最后,您需要使用外部函数的所有参数调用内部函数。

一个小提示,只取一个小写字母,因为没有不可实现的功能。

&#13;
&#13;
function multiply(...args) {
    function m(f, ...a) {
        p *= f;
        if (a.length) {
            m(...a);
        }
        return m;
    }

    var p = 1;            // neutral value for multiplication
    m.toString = _ => p;
    return m(...args);
}

console.log(multiply(5)(5)(6)(8));
console.log(multiply(2, 3, 4)(5)(6, 7));
&#13;
&#13;
&#13;

答案 1 :(得分:3)

  1. The function returned by Map<String, String> should return itself after each call.
  2. order_line map<text, frozen<map<text, text>>> should be assigned to that function not to its argument which will be a number.
  3. Multiply should call the inner function with its argument (the initial number).
  4. No need to use the valueOf object as there will always be one argument.

Multiply

Note: The arguments in function Multiply(initialNum) { var product = 1; function fn(num) { product *= num; return fn; }; fn.valueOf = function() { return product; }; return fn(initialNum); } console.log(0 + Multiply(5)(5)(6)(8)); is to assure that 0 + will be called as the SO snippett console doesn't seem to work properly.

答案 2 :(得分:1)

You can implement it by overwriting Function#toString method which would call internally in major caser(for eg: while using with sudo python3 setup.py install function, string concatenation, etc...).

import pandas as pd
one = pd.read_csv("~/Documents/2017Data/2017DATA.csv")