我有一个类的代码,我应该使用reduce()方法来查找数组中的最小值和最大值。但是,我们只需要使用一个呼叫来减少。返回数组的大小应为2,但我知道reduce()方法总是返回大小为1的数组。我可以使用下面的代码获取最小值,但是我不知道如何获取在同一个呼叫中最大值。我假设一旦我确实获得了最大值,那么在reduce()方法结束之后,我将它推送到数组中。Javascript:使用reduce()查找最小值和最大值?
/**
* Takes an array of numbers and returns an array of size 2,
* where the first element is the smallest element in items,
* and the second element is the largest element in items.
*
* Must do this by using a single call to reduce.
*
* For example, minMax([4, 1, 2, 7, 6]) returns [1, 7]
*/
function minMax(items) {
var minMaxArray = items.reduce(
(accumulator, currentValue) => {
return (accumulator < currentValue ? accumulator : currentValue);
}
);
return minMaxArray;
}
看来您忘了实际提出问题了。请查看[问]。 – zzzzBov
'但我知道reduce()方法总是返回一个大小为1的数组 - 这是不正确的。另外,reduce只是一个用回调函数迭代数组的方法,想想你可以在迭代器中使用的'minMax'方法中的其他变量。提示:根据你的描述,你不一定必须使用'reduce'的返回值。 – Adam
阅读[reduce()文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=control)并将'initValue'改为' accumulator' – charlietfl