javascript - JavaScript 如何创建一个函数,该函数返回一个字符串,其中一个字符在字符串中出现的次数
问题描述
我试图弄清楚如何制作一个带字符串的函数。然后它需要返回一个字符串,其中包含函数中出现的每个字母以及它在字符串中出现的次数。例如“eggs”应该返回 e1g2s1。
function charRepString(word) {
var array = [];
var strCount = '';
var countArr = [];
// Need an Array with all the characters that appear in the String
for (var i = 0; i < word.length; i++) {
if (array.indexOf(word[i]) === false) {
array.push(word[i]);
}
}
// Need to iterate through the word and compare it with each char in the Array with characters and save the count of each char.
for (var j = 0; j < word.length; i++) {
for (var k = 0; k < array.length; k++){
var count = 0;
if (word[i] === array[k]){
count++;
}
countArr.push(count);
}
// Then I need to put the arrays into a string with each character before the number of times its repeated.
return strCount;
}
console.log(charRepString("taco")); //t1a1co1
console.log(charRepString("egg")); //e1g2
解决方案
let str = prompt('type a string ') || 'taco'
function getcount(str) {
str = str.split('')
let obj = {}
for (i in str) {
let char = str[i]
let keys = Object.getOwnPropertyNames(obj)
if (keys.includes(char)) {
obj[char] += 1
} else {
obj[char] = 1
}
}
let result = ''
Object.getOwnPropertyNames(obj).forEach((prop) => {
result += prop + obj[prop]
})
return result
}
console.log(getcount(str))
推荐阅读
- debian - 禁用 qemu 默认快捷方式
- c++ - qtextedit 设置仅当光标放在其上时才显示的文本
- python - Python 3.9.4 如何在大字符串中查找文本
- solr - Why does starting Solr with multiple Zookeeper IPs fail?
- python - python matplotlib没有按顺序绘制y轴
- python - 前序二叉树遍历递归方法
- javascript - Angular 9 应用程序未在 IE11 中加载
- javascript - 正则表达式长度取决于值和小数
- json - 无法将字符串从 .csv 转换为浮点数
- html - iOS Safari 中的 HTML 音频元素显示奇怪