從 JavaScript 字串陣列中查詢最小元素
我們需要編寫一個 JavaScript 函式來接收一個字串陣列,並返回長度最短的字串的索引。
我們將簡單地使用一個 for 迴圈,並儲存長度最短的字串的索引。
因此,讓我們編寫此函式的程式碼 −
例項
其程式碼如下 −
const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];
const findSmallest = arr => {
const creds = arr.reduce((acc, val, index) => {
let { ind, len } = acc;
if(val.length < len){
len = val.length;
ind = index;
};
return { ind, len };
}, {
ind: -1,
len: Infinity
});
return arr[creds['ind']];
};
console.log(findSmallest(arr));輸出
控制檯中的輸出如下 −
be
廣告
資料結構
網路
關係型資料庫
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP