使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP