最近我拿起一本叫Javascript的书来学习这门语言。我在某些章节和主题上苦苦挣扎。
const foldWith = (fn, terminalValue, [first, ...rest]) =>
first === undefined
? terminalValue
: fn(first, foldWith(fn, terminalValue, rest));现在,我理解了ES6函数声明、调用或调用,但我对foldWith被调用更多“内部参数”的事实感到困惑。在下一个代码中:
foldWith((number, rest) => number * number + rest, 0, [1, 2, 3, 4, 5])我似乎不知道foldWith((number, rest)、number和rest是如何决定参数的哪一部分的?我的意思是用4个参数创建的foldWith函数,用4个参数调用,但是number是如何链接到first和rest到rest的
发布于 2021-04-02 09:21:29
foldWith是一个递归函数(有时会调用它自己),它使用参数析构。毁灭就在这里:
const foldWith = (fn, terminalValue, [first, ...rest]) =>
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^它接受它接收的第三个参数,它是示例调用中的一个数组,并且:
rest.
first中,
first中的一个新数组中。这被称为迭代析构(有时人们称它为“数组析构”,但并不局限于数组)。
对于第一个调用,数组是[1, 2, 3, 4, 5],所以first获取1,rest获得一个带有[2, 3, 4, 5]的新数组。
那就是那部分。接下来是递归。让我们再看看这个函数(添加了一些格式):
const foldWith = (fn, terminalValue, [first, ...rest]) =>
first === undefined
? terminalValue
: fn(first, foldWith(fn, terminalValue, rest));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−− recursive callfoldWith自称为。最初,它是以[1, 2, 3, 4, 5]作为第三个参数调用的,因此:
first是1 (而不是undefined),rest是[2, 3, 4, 5]。由于first不是undefined,在调用过程中,foldWith以[2, 3, 4, 5]作为fn(first, foldWith(fn, terminalValue, rest)):first是2,rest是[3, 4, 5],因此它再次调用自己为fn(first, foldWith(fn, terminalValue, rest)):f<137/code>H 138,D 39是3,D41是[4, 5],因此它再次调用自己为fn(first, foldWith(fn, terminalValue, rest)):H 145在调用期间D46>是代码>代码>代码>代码>代码>代码>代码>代码>因此,在调用期间,它再次作为fn(first, foldWith(fn, terminalValue, rest)):的一部分调用自己,first是5,rest是[],因此在调用期间再次调用自己为fn(first, foldWith(fn, terminalValue, rest)):H 159的一部分,first is undefined (因为如果尝试从空数组中获取第一个元素,则得到undefined)和rest是[]。所以foldWith并不是自己。相反,它返回值terminalValue.
。
- The rest of `fn(first, foldWith(fn, terminalValue, rest))` can now be done, with `terminalValue` where the `foldWith` call was. So it's effectively `fn(first, terminalValue)`; it returns that result. - That result is now used in `fn(first, <<previous result>>)` and that result is returned - Same again, that result is now used in `fn(first, <<previous result>>)` and that result is returned- Same again调用返回fn.的最终结果
让我们来想象一下:
let indent = 0;
function log(...msgs) {
console.log(`${" ".repeat(indent)}${msgs.join(" ")}`);
}
const foldWith = (fn, terminalValue, [first, ...rest]) => {
log(`foldWith(fn, ${terminalValue}, ${first === undefined ? "[]" : JSON.stringify([first, ...rest])})`);
// log(first === undefined ? `* Returning ${terminalValue}` : `Recursing`);
++indent;
const result = first === undefined
? terminalValue
: fn(first, foldWith(fn, terminalValue, rest));
--indent;
log(`foldWith returning ${result}`);
return result;
};
const fn = (number, rest) => {
const result = number * number + rest;
log(`fn(${number}, ${rest}) is ${result}`);
return result;
}
const final = foldWith(fn, 0, [1, 2, 3, 4, 5])
log(`Final result: ${final}`);.as-console-wrapper {
max-height: 100% !important;
}
https://stackoverflow.com/questions/66916763
复制相似问题