我有一個類的代碼,我應該使用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