确定字符串中的字符频率(Javascript)

时间:2014-02-03 04:17:16

标签: javascript

我正在研究确定字符串中字符频率的解决方案。正确地将字符添加到我的对象中,但所有计数最终都是NaN。 (我认为我通过将字符串拆分成一个字符数组来采用效率较低的方法,但我仍然想解决这个问题。)

var charFreq = function (frequencyString) {
    var stringArray = frequencyString.split("");
    var frequencies = {};
    for (var k in stringArray) {
        var nowLetter = stringArray[k];
        if (stringArray.hasOwnProperty(k)) {
            frequencies[nowLetter] += 1;
        }
    }
    return frequencies;
}

charFreq("what is the reason for this"); 

8 个答案:

答案 0 :(得分:4)

您的frequencies是一个对象,当您访问时

frequencies[nowLetter] += 1;

您正在访问以前不可用的属性,例如frequencies.aundefined。因此,你得到了NaN。

有关此修复程序,请参阅http://jsfiddle.net/xbUtR/

if(frequencies[nowLetter] === undefined)
                frequencies[nowLetter] = 0;
            frequencies[nowLetter] += 1;

答案 1 :(得分:3)

您的代码中未定义

frequencies[nowLetter]

更好的方法:

function charFreq(txt){
    var obj = {};
    for(var i = 0; i < txt.length; i++){
        obj[txt[i]] = ++obj[txt[i]]||1;
    }
    return obj;
}

答案 2 :(得分:3)

因为frequencies中的属性值的初始值为undefinedundefined + 1 == NaN

尝试这样的代码:

var charFreq = function (frequencyString) {
    var stringArray = frequencyString.split("");
    var frequencies = {};
    for (var k in stringArray) {
        var nowLetter = stringArray[k];
        if (stringArray.hasOwnProperty(k)) {

            // One way to initialize the value -- not the only way.
            if (!frequencies[nowLetter]) {
              frequencies[nowLetter] = 0;
            }

            frequencies[nowLetter] += 1;
        }
    }
    return frequencies;
}

答案 3 :(得分:1)

有许多方法,特别是如果效率不是一个问题:

var frequencies = function (s) {
    var f = {};
    s.split("").forEach(function (e, i, a) {
        f[e] = f[e] || 0;
        f[e] += 1;
    });
    return f;
}

调用frequencies("thiss")会产生Object {t: 1, h: 1, i: 1, s: 2}

答案 4 :(得分:0)

您可以在不创建数组的情况下单步执行字符。

var charFreq= function(frequencyString){
    var next, i= 0, frequencies= {},
    L= frequencyString.length;
    while(i<L){
        next= frequencyString.charAt(i++);
        if(!frequencies[next]) frequencies[next]= 0;
        ++frequencies[next];
    }
    return frequencies;
}

//demo 
JSON.stringify(charFreq("what is the reason for this"));

/*  returned value: (String)
{"w":1,"h":3,"a":2,"t":3," ":5,"i":2,"s":3,"e":2,"r":2,"o":2,"n":1,"f":1}

* /

答案 5 :(得分:0)

带有胖箭=>

An Introduction to Functional Programming - Coding School Presentation

var charFreq = (string) =>
   string
        .split('')
        .sort()
        .join('')
        .match(/(\w)\1*/g)
        .map(letters => [letters[0], letters.length])
        .sort((a,b) => {
                return a[1] !== b[1] ? (a[1] < b[1]) : (a[0] > b[0]);
        })

console.log(charFreq('what is the reason for this'));

答案 6 :(得分:0)

function highestFreqChar(str) {
    var charMap = {};
  for (var i=0; i<str.length; i++) {
    var character = str.charAt(i);
    if (charMap[character]) {
        charMap[character]++;
    } else {
        charMap[character] = 1;
    }
  }

  var max = -1;
  var result = "";
  for (var j=0; j<str.length; j++) {
    if (max < charMap[str.charAt(j)]) {
        max = charMap[str.charAt(j)];
      result = str.charAt(j);
    }
  }
  return {result : result, charmap: charMap};
}

答案 7 :(得分:0)

function calculateFrequency(string) {
const alphabet ='abcdefghijklmnopqrstuvwxyz'
const alphabetUp = alphabet.toUpperCase()
let freq=[26] 
for(let i in alphabet){
   freq[i]=0
    for(let j in string ){
         if(alphabet[i] == string[j] || alphabetUp[i] == string[j] ){
        freq[i] = freq[i] + 1
        }
    }

    if(freq[i] != 0){
        console.log(alphabet[i] + ' : ' + freq[i])
    }
 }
}

无论大小写(上下),这种方法都可以计算字符数