将字符串中的唯一字符映射到数组 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/11 13:32:17
我们需要编写一个 JavaScript 函数,该函数接收一个字符串并从 0 开始映射其字符。每当函数遇到唯一(非重复)字符时,它应该将映射计数增加 1,否则将为重复字符映射相同的数字。
例如 − 如果字符串是 −
const str = 'heeeyyyy';
那么输出应该是 −
const output = [0, 1, 1, 1, 2, 2, 2, 2];
示例
以下是代码 −
const str = 'heeeyyyy';
const mapString = str => {
const res = [];
let curr = '', count = -1;
for(let i = 0; i < str.length; i++){
if(str[i] === curr){
res.push(count);
}else{
count++;
res.push(count);
curr = str[i];
};
};
return res;
};
console.log(mapString(str));
输出
以下是控制台中的输出 −
[ 0, 1, 1, 1, 2, 2, 2, 2 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

