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

问题描述 投票:0回答:2

例如输入"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. 我是否将字符串视为数组或对象?对于对象,如何开始将它们分解为单词并迭代计数?

javascript jasmine
2个回答
4
投票

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.prototypeString.prototype


0
投票

这是您的操作方式

word-count.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;
© www.soinside.com 2019 - 2024. All rights reserved.