查找数组中最短的字符串 - 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP