簡體   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