首页 > 解决方案 > 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

标签: javascript

解决方案


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))


推荐阅读