.push() 和 .reduce() 在这里如何协同工作? (斐波那契)
How do .push() and .reduce() work together here? (fibonacci)
我完成了一项作业,其中函数的输出是斐波那契数组的最后一个数字。说实话,我在这个问题上遇到了困难,我在 Whosebug 上的第二个 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
returns 是一个数组而不是单个值?既然它 returns 是一个数组 - 为什么 push
的数字不会被添加到初始数组中,它已经有值了? -> 让我们说 input = 4
然后 filled = [1, 1, 1, 1]
.
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;
},[]); // <- reduce is initialized with an array (new array),
return reduced[n - 1] + reduced[n - 2];
}
}
由于 reduce 是用一个新数组初始化的,该函数正在减少(向新初始化数组添加新值)并返回相同的值。
这里是减速器的工作原理
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
我完成了一项作业,其中函数的输出是斐波那契数组的最后一个数字。说实话,我在这个问题上遇到了困难,我在 Whosebug 上的第二个 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
returns 是一个数组而不是单个值?既然它 returns 是一个数组 - 为什么 push
的数字不会被添加到初始数组中,它已经有值了? -> 让我们说 input = 4
然后 filled = [1, 1, 1, 1]
.
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;
},[]); // <- reduce is initialized with an array (new array),
return reduced[n - 1] + reduced[n - 2];
}
}
由于 reduce 是用一个新数组初始化的,该函数正在减少(向新初始化数组添加新值)并返回相同的值。
这里是减速器的工作原理 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce