查找数组中最短的字符串 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/30 17:48:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

