使用 JavaScript 在間隔有空格的數字字串中查詢最大和最小數字


問題

我們需要編寫一個 JavaScript 函式,該函式接收一個字串,其中包含用空格分隔的數字。

我們的函式應該返回一個字串,其中只包含用空格分隔的最大和最小數字。

輸入

const str = '5 57 23 23 7 2 78 6';

輸出

const output = '78 2';

因為 78 是最大數字,2 是最小數字。

示例

以下是程式碼 -

 現場演示

const str = '5 57 23 23 7 2 78 6';
const pickGreatestAndSmallest = (str = '') => {
   const strArr = str.split(' ');
   let creds = strArr.reduce((acc, val) => {
   let { greatest, smallest } = acc;
   greatest = Math.max(val, greatest);
   smallest = Math.min(val, smallest);
   return { greatest, smallest };
}, {
      greatest: -Infinity,
      smallest: Infinity
   });
   return `${creds.greatest} ${creds.smallest}`;
};
console.log(pickGreatestAndSmallest(str));

輸出

78 2

更新時間: 2021-04-17

265 次瀏覽

開啟您的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.