查找数组中最长的字符串(不包括空格)JavaScript
我们需要编写一个函数,该函数接受字符串文字的数组并返回数组中最长字符串的索引。在计算字符串的长度时,我们不必考虑空格所占的长度
如果两个或多个字符串的最长长度相同,我们必须返回这样做的第一个字符串的索引。
我们将遍历数组,通过空格将每个元素拆分,再次连接并计算长度,然后将其存储在对象中。当遇到的长度大于当前存储在对象中的长度时,我们对其进行更新,最后返回索引。
示例
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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短