从 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