查找字符串中每个字符的确切数量

Finding exact amount of each character in a string

本文关键字:字符 字符串 查找      更新时间:2023-09-26

所以我遇到了一个非常复杂的面试问题(至少对我来说),我还没能找到答案。如下所示:

编写一个函数,该函数接受一个字符串并返回一个对象,其中键是特定的字母,值是在字符串中找到特定字母的次数。例如:

myfn('My name is Taylor');
newObj{
a: 2,
e: 1,
i: 1,
l: 1,
m: 2,
n: 1,
o: 1,
r: 1,
s: 1,
t: 1,
y: 2
}

CCD_ 1是它正在返回的。

此函数将字符串作为其参数。

function getObj(str) {
    //define a new object
    var obj = {};
    // loop over the string
    for (var i = 0, l = str.length; i < l; i++) {
      // set the letter variable to the element the loop is on
      // drop the letter to lowercase (if you want to
      // record capitalised letters too drop the
      // `.toLowerCase()` part)
      var letter = str[i].toLowerCase();
      // if the key doesn't exist on the object create a new one,
      // set to the letter and set it to zero
      if (!obj[letter]) { obj[letter] = 0; }
      // increment the number for that key (letter)
      obj[letter]++;
    }
    // finally return the object
    return obj;
}
var obj = getObject(str);

DEMO

我想我想通了。

var myFn = function(str){
  var newObj = {};
  for(var i = 0; i<str.length; i++){
    if(newObj[str[i]]){
      newObj[str[i]]++;
    } else{
      newObj[str[i]] =1;
    }
  }
  return newObj;
}

已针对拼写错误和语法进行编辑