简体   繁体   English

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

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

For example for the input "olly olly in come free"例如对于输入"olly olly in come free"

The program should return:程序应该返回:

olly: 2 in: 1 come: 1 free: 1

The tests are written as:测试写成:

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. How do I start in my word-count.js file?如何从 word-count.js 文件开始? Create a method words() or a module Words() and make an expectedCount method in there and export it?创建一个方法 words() 或模块 Words() 并在其中创建一个 expectedCount 方法并导出它?

  2. Do I treat the string as an array or an object?我将字符串视为数组还是对象? In the case of objects, how do I start breaking them into words and iterate for the count?在对象的情况下,我如何开始将它们分解成单词并迭代计数?

 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"));

This code should get just what you want.这段代码应该得到你想要的。
For more understanding on the code I would advice you to go through array prototype functions and string prototype functions.为了对代码有更多的理解,我建议你通过数组原型函数和字符串原型函数。
For simple understanding of what I`m doing here:为了简单理解我在这里做什么:

  1. Create a count function which returns an object of count of all occurrences of words.创建一个计数函数,该函数返回所有出现单词的计数对象。
  2. Split the string using split(" ") based on a space which gives an array.基于给出数组的空格使用split(" ")拆分字符串。
  3. Use forEach method to iterate through all the elements in the spitted array.使用forEach方法遍历吐出数组中的所有元素。
  4. Ternary operator :?三元运算符:? to check if value already exists, if it does increment by one or assign it to 1.检查值是否已经存在,如果它增加 1 或将其分配给 1。

Array.prototype String.prototype Array.prototype String.prototype

Here's how you do it这是你如何做到的

word-count.js字数统计.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