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

时间:2014-09-13 17:47:15

标签: javascript function object

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

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

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
}

newObj就是它的回归。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

我想我已经明白了。

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;
}

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