查找一个数组中(空间除外)最长的字符串
我们需写一个函数,接受一个字符串字面量数组并返回其中最长的字符串的索引。在计算字符串长度时,我们不必考虑空白所占用的长度
如果两个或两个以上的字符串有相同的最大长度,我们要返回最先这样做的字符串的索引。
我们将遍历该数组,按空格拆分每项,然后重新连接它们并计算长度,在此之后,我们将把它存储在对象中。当我们遇到长度大于对象中当前保存的长度时,我们将更新它,最后返回索引。
示例
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP