有一条线。
const stringCount = "ggggaaaazzzzzlllllluuuuuuuuu";
任务是编写一个函数来计算字符数并返回这样的结果g4a4z5l6u9
我得到了以下非工作代码
const str = "ggggaaaazzzzzlllllluuuuuuuuu";
const strNumeric = (str) => {
let counter = 0,
currentItem = str[0],
arr = [];
[...str].forEach((iterator) => {
if (iterator !== currentItem) {
currentItem = iterator;
arr = [...arr, `${currentItem}${counter}`];
counter = 0;
} else {
counter += 1;
}
});
console.log(arr);
};
console.log(strNumeric(str));
执行此代码的结果是
[
"a4",
"z3",
"l4",
"u5"
]
第二次尝试
const str = "ggggaaaazzzzzlllllluuuuuuuuu";
const strNumeric = (str) => {
let main = [],
count = 0,
arr = [];
[...str].forEach((a) => {
if (!arr.includes(a)) {
count = str.match(/a/g, "").length;
arr = [...arr, a];
main = [...main, `${a}${count}`];
} else {
count = 0;
}
});
console.log(main);
};
strNumeric(str);
它非常接近这里的解决方案。
我教这样一个数组-> ["g4", "a4", "z4", "l4", "u4"]
问题出在这一行->count = str.match(/a/g, "").length;
在这里,出于某种原因,我总是得到 4。为什么还不清楚。
我希望看到一个更易于理解的实现,请不要使用单行函数和单字符变量。
我的想法是这样的:在一个循环中计数成一个关联数组,其中键是一个字符,值是字符串中的字符数。很抱歉简化了您的代码。我不知道宝贝。
如果字母被分组:
如果同一个字母有多个组:
解决方案:
谢谢大家的回复,大家点赞。
有点类似于@Igor 的回答——我
还有一种替代算法可以做相反的事情
由此
"g4a4z5l6u9"
使这个->"ggggaaaazzzzzlllllluuuuuuuuu"
稍后我将在第二个代码中添加注释。
我给你写了一个函数,它会返回一个对象,现在你可以用这个数据做任何你想做的事情。
试试这样: