在 JavaScript 中查找字符串数组中的最小元素

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/8 21:00: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

相关文章


有用资源