MST
星途 面试题库

面试题:JavaScript字符串处理中的复杂操作

假设有一个包含多个单词的长字符串,单词之间用空格分隔,同时字符串两端可能存在多余空格。请编写一个函数,该函数接受这个字符串作为参数,返回一个对象,对象包含以下属性:1. 'wordCount',表示字符串中的单词数量;2. 'longestWord',表示字符串中最长的单词;3. 'averageWordLength',表示单词的平均长度(四舍五入保留一位小数)。要求使用JavaScript字符串处理方法高效实现。
10.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function analyzeString(str) {
    // 去除两端空格并按空格分割字符串
    const words = str.trim().split(' ');
    let wordCount = words.length;
    let longestWord = '';
    let totalLength = 0;

    words.forEach(word => {
        if (word.length > longestWord.length) {
            longestWord = word;
        }
        totalLength += word.length;
    });

    let averageWordLength = wordCount === 0? 0 : Math.round(totalLength / wordCount * 10) / 10;

    return {
        wordCount,
        longestWord,
        averageWordLength
    };
}