繁体   English   中英

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

[英]Count the occurrence of each word in a phrase using javascript

例如对于输入"olly olly in come free"

程序应该返回:

olly: 2 in: 1 come: 1 free: 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
});
  1. 如何从 word-count.js 文件开始? 创建一个方法 words() 或模块 Words() 并在其中创建一个 expectedCount 方法并导出它?

  2. 我将字符串视为数组还是对象? 在对象的情况下,我如何开始将它们分解成单词并迭代计数?

 function count(str) { var obj = {}; str.split(" ").forEach(function(el, i, arr) { obj[el] = obj[el] ? ++obj[el] : 1; }); return obj; } console.log(count("olly olly in come free"));

这段代码应该得到你想要的。
为了对代码有更多的理解,我建议你通过数组原型函数和字符串原型函数。
为了简单理解我在这里做什么:

  1. 创建一个计数函数,该函数返回所有出现单词的计数对象。
  2. 基于给出数组的空格使用split(" ")拆分字符串。
  3. 使用forEach方法遍历吐出数组中的所有元素。
  4. 三元运算符:? 检查值是否已经存在,如果它增加 1 或将其分配给 1。

Array.prototype String.prototype

这是你如何做到的

字数统计.js

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM