查找数组中最长的字符串(不包括空格)JavaScript

javascriptweb developmentobject oriented programming更新于 2025/9/30 7:08:17

我们需要编写一个函数,该函数接受一个字符串文字数组并返回数组中最长的字符串的索引。在计算字符串长度时,我们不必考虑空格所占的长度

如果两个或多个字符串具有相同的最长长度,我们必须返回第一个字符串的索引。

我们将遍历数组,用空格分割每个元素,再次连接并计算长度,之后我们将其存储在一个对象中。当我们遇到大于当前存储在对象中的长度时,我们会更新它,最后返回索引。

示例

const arr = ['Hello!', 'How are you', 'Can ', 'I use', 'splice method
with', ' strings in Js?'];
const findLongestIndex = (arr) => {
   const index = {
   '0': 0
};
const longest = arr.reduce((acc, val, index) => {
   const actualLength = val.split(" ").join("").length;
   if(actualLength > acc.length){
      return {
         index,
         length: actualLength
      };
   }
   return acc;
   }, {
      index: 0,
      length: 0
   });
   return longest.index;
};
console.log(findLongestIndex(arr));

输出

控制台中的输出将是 −

4

相关文章


有用资源