猿问

.push() 和 .reduce() 在这里如何协同工作?

我已经完成了一项作业,其中函数的输出是斐波那契数组的最后一个数字。说实话,我在这个问题上陷入了困境,我在 stackoverflow 上的第二个 else if 语句中找到了代码。但我无法理解它到底是如何工作的。


这是代码:


const fibonacci = function(input) {

    let n = Number(input);

        if (n === 1) {

            return 1;

        } else if (n < 1) {

            return "OOPS";

        } else if (n > 1) {

            let array = new Array(n);                              // <---- Starting here

            let filled = array.fill(1);

            let reduced = filled.reduce((acc, _, i) => {

                acc.push((i <=1) ? i : acc[i-2] + acc[i-1])

                    return acc;                          

            },[]);

return reduced[n - 1] + reduced[n - 2];

        }

我的问题:为什么reduced返回一个数组而不是单个值?既然它返回一个数组 - 为什么push'ed 数字不会添加到初始数组中,其中已经有值了?input = 4->那么我们就说吧filled = [1, 1, 1, 1]



www说
浏览 86回答 1
1回答

陪伴而非守候

const fibonacci = function(input) {&nbsp; &nbsp; let n = Number(input);&nbsp; &nbsp; &nbsp; &nbsp; if (n === 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; &nbsp; &nbsp; } else if (n < 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "OOPS";&nbsp; &nbsp; &nbsp; &nbsp; } else if (n > 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let array = new Array(n);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // <---- Starting here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let filled = array.fill(1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let reduced = filled.reduce((acc, _, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; acc.push((i <=1) ? i : acc[i-2] + acc[i-1])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return acc;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },[]); // <- reduce is initialized with an array (new array),return reduced[n - 1] + reduced[n - 2];&nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp;由于reduce是用新数组初始化的,因此该函数正在减少(将新值添加到新的初始化数组中)并返回相同的值。这里的减速器是如何工作的&nbsp;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答