使用javascript计算短语中每个单词的出现次数

使用javascript计算短语中每个单词的出现次数,javascript,jasmine,Javascript,Jasmine,例如,在come free中输入olly olly 程序应返回: 奥利:2 年:1 来:1 免费:1 测试内容如下: var words = require('./word-count'); describe("words()", function() { it("counts one word", function() { var expectedCounts = { word: 1 }; expect(words("word")).toEqual(expectedCo

例如,在come free中输入olly olly

程序应返回:

奥利:2 年:1 来:1 免费:1

测试内容如下:

var words = require('./word-count');

describe("words()", function() {
  it("counts one word", function() {
    var expectedCounts = { word: 1 };
    expect(words("word")).toEqual(expectedCounts);
  });

//more tests here
});
如何从word-count.js文件开始?创建方法Word或模块Word,并在其中创建expectedCount方法并将其导出

我是将字符串视为数组还是对象?对于对象,我如何开始将它们分解为单词并迭代计数

函数countstr{ var obj={}; str.split.Foreachel,i,arr{ obj[el]=obj[el]?++obj[el]:1; }; 返回obj; } console.logcountolly-olly-in-come-free 函数countstr{ var obj={}; str.split.Foreachel,i,arr{ obj[el]=obj[el]?++obj[el]:1; }; 返回obj; } console.logcountolly-olly-in-come-free 这是你怎么做的

word-count.js

这是你怎么做的

word-count.js


xBrowser注:forEach在第5版中添加到ECMA-262标准中,如果需要使其不区分大小写el=el.toLowerCase;maybe help.xBrowser注意:forEach在第5版中被添加到ECMA-262标准中,如果您需要使其不区分大小写el=el.toLowerCase;也许会有帮助。
function word-count(phrase){
    var result = {};  // will contain each word in the phrase and the associated count
    var words = phrase.split(' ');  // assuming each word in the phrase is separated by a space

    words.forEach(function(word){
        // only continue if this word has not been seen before
        if(!result.hasOwnProperty(word){
            result[word] = phrase.match(/word/g).length;
        }
    });

    return result;
}

exxports.word-count = word-count;