gpt4 book ai didi

javascript - 使用 toString 方法和递归对数字求和的函数的说明

转载 作者:行者123 更新时间:2023-11-29 20:59:24 25 4
gpt4 key购买 nike

我正在学习 JS,并且想了解我遇到的这个例子:

function sum(a) {

let currentSum = a;

function f(b) {
currentSum += b;
return f;
}

f.toString = function() {
return currentSum;
};

return f;
}

console.log( sum(1) ); // f 1
console.log( sum(1)(2) ); // f 3
console.log( sum(5)(-1)(2) ); // f 6
console.log( sum(6)(-1)(-2)(-3) ); // f 0
console.log( sum(0)(1)(2)(3)(4)(5) ); // f 15

我不明白的是这个函数是如何只通过调用 sum(1) 返回 antyhing 的,而我认为因为我们只返回第一次调用的函数?另外,这个 toString 方法到底在做什么,它是如何给出 f 1 等等结果的?我真的希望有人能解释这一点,因为我无法理解教程中这段代码的内容。如果问题是给菜鸟的,请道歉。

最佳答案

当您记录函数的结果时,它需要将该结果转换为字符串。一些浏览器通过调用它的 .toString() 方法来做到这一点。

sum() 返回一个函数,该函数将其参数添加到闭包中的 currentSum 变量。这就是链式函数调用累加总数的方式。但是这个函数还有一个自定义的 .toString() 方法,它返回计算出的总和,所以这就是记录的内容。

我们可以像这样分解其中一条长链:

console.log(sum(1)(2)(3));

相当于:

temp1 = sum(1); // sets currentSum to 1, returns f
temp2 = temp1(2); // sets currentSum to 3, returns f
temp3 = temp2(3); // sets currentSum to 6, returns f
console.log(temp3); // calls f.toString(), which returns currentSum, so 6 is printed

这是一个可爱的技巧,但它不是允许像这样的链式调用的有用的通用方法。这取决于这样一个事实,即在所有调用完成后,最终结果将被需要字符串的东西使用。它取决于 console.log() 的浏览器特定功能——它在 Firefox 中不起作用。

关于javascript - 使用 toString 方法和递归对数字求和的函数的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47359833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com