使用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
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
});
-
如何从我的word-count.js文件开始?创建方法words()或模块Words()并在其中创建一个ExpectedCount方法并将其导出?
How do I start in my word-count.js file? Create a method words() or a module Words() and make an expectedCount method in there and export it?
我将字符串视为数组还是对象?对于对象,如何开始将它们分解为单词并迭代计数?
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:
- 创建一个count函数,该函数返回所有出现的单词的计数对象.
- 使用
split(" ")
根据给出数组的空格分割字符串. - 使用
forEach
方法来迭代分散数组中的所有元素. - 三元运算符
:?
来检查值是否已存在,是否确实增加了1或将其分配给了1.
- Create a count function which returns an object of count of all occurrences of words.
- Split the string using
split(" ")
based on a space which gives an array. - Use
forEach
method to iterate through all the elements in the spitted array. - Ternary operator
:?
to check if value already exists, if it does increment by one or assign it to 1.
Array.prototype String.prototype
这篇关于使用javascript计算短语中每个单词的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!