在 JavaScript 中尋找字串中的最短單詞
我們需要編寫一個 JavaScript 函式,該函式接收一個字串並返回該字串中的最短單詞。
例如:如果輸入字串為 −
const str = 'This is a sample string';
則輸出應為 −
const output = 'a';
示例
此程式碼為 −
const str = 'This is a sample string';
const findSmallest = str => {
const strArr = str.split(' ');
const creds = strArr.reduce((acc, val) => {
let { length, word } = acc;
if(val.length < length){
length = val.length;
word = val;
};
return { length, word };
}, {
length: Infinity,
word: ''
});
return creds.word;
};
console.log(findSmallest(str));輸出
控制檯中的輸出 −
a
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP