js如何找出空格分割的字符串里最大单词长度?例如 hello my friend,怎么计算出最大单词长度为friend 6?
网友回复
要找出用空格分割的字符串中最大单词的长度,可以使用JavaScript中的字符串和数组方法来实现。以下是一个简单的示例代码:
function findMaxWordLength(str) { // 使用空格分割字符串为单词数组 const words = str.split(' '); // 初始化最大长度为0 let maxLength = 0; // 遍历单词数组,找出最大长度 for (let word of words) { if (word.length > maxLength) { maxLength = word.length; } } return maxLength; } // 示例用法...
点击查看剩余70%