例如输入"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
});
我如何开始我的word-count.js文件?创建方法words()或模块Words()并在其中创建一个ExpectedCount方法并将其导出?
我是否将字符串视为数组或对象?对于对象,如何开始将它们分解为单词并迭代计数?
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"));
此代码应该可以得到您想要的。为了对代码有更多的了解,我建议您遍历数组原型函数和字符串原型函数。为了简单地了解我在这里做什么:
split(" ")
根据给出数组的空格分割字符串。forEach
方法遍历分散数组中的所有元素。:?
检查值是否已经存在,是否确实增加了1或将其分配给了1。这是您的操作方式
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;