简体   繁体   English

咖喱和封闭?

[英]Currying and closure?

I am having trouble understanding the behavior of this code. 我在理解此代码的行为时遇到了麻烦。 The num parameter and array parameter seem to be acting differently and I am not sure what is causing it. num参数和array参数的行为似乎有所不同,我不确定是什么原因引起的。 So, the num parameter keeps track of how many times the curried function has been called, and you can go back up the curry chain and it will retain the correct num and let you go back down the chain with a new input. 因此,num参数跟踪已调用了curried函数的次数,您可以返回curry链,它将保留正确的num,并让您使用新的输入返回链。 I would think that array would act the same way, but array keeps accumulating inputs and I am not sure what is causing it as like num, I am binding whatever its current value is just like I am with num. 我认为数组会以相同的方式工作,但是数组会不断累积输入,并且我不确定是什么原因导致它像num一样,我绑定的是它的当前值,就像使用num一样。

function curryN(fn, n) {
    n = n || fn.length;
    return function curried(num, array, input) {
        console.log(array);
        num = num || n;
        array.push(input);
        num--;
        console.log(num);
        while (num >= 1) {
            return curried.bind(this, num, array)
        }
        var tempArray = array;
        return fn.apply(this, tempArray)
    }.bind(this, n, [])
}

function abc(one, two, three) {
    return one/two/three;
}

var curryC = curryN(abc),
    curryB = curryC(81),
    curryA = curryB(9);

Im not entirely sure what you are asking, but I think you are asking why when you push letters into the array, they appear as numbers. 我不确定您要问的是什么,但我想您是在问为什么将字母推入数组时它们会显示为数字。

If you are pushing a string to that array, wrap it in quotes so that the compiler knows you want the letters stored as a string, and not its numerical equivalent. 如果要将字符串推入该数组,则将其用引号引起来,以便编译器知道要将字母存储为字符串,而不是数字形式的等效字符。 Normally values don't need to be typed in Javascript, but if you are using an mixed array you need to let the compiler know you want it to remain a string. 通常,不需要在Javascript中键入值,但是如果您使用混合数组,则需要让编译器知道您希望它保留为字符串。

for example, 例如,

var curryC = curryN(abc)

should be 应该

var curryC = curryN("abc")

If this is completely not what you are asking, then please explain what desired output you are looking for. 如果这完全不是您要的内容,请说明您要寻找的期望输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM