MST

星途 面试题库

面试题:JavaScript 中字符串与数组兼容性处理之基础操作

在JavaScript中,我们常把字符串当作类似数组的对象来操作。请编写一个函数,接收一个字符串,返回该字符串中每个字符出现的次数,要求使用字符串类似数组的特性(如通过索引访问字符)来实现。例如,输入字符串 'hello',返回对象 {'h': 1, 'e': 1, 'l': 2, 'o': 1}。
40.5万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function countChars(str) {
    const result = {};
    for (let i = 0; i < str.length; i++) {
        const char = str[i];
        if (result[char]) {
            result[char]++;
        } else {
            result[char] = 1;
        }
    }
    return result;
}