例如,对于输入"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
});发布于 2014-11-09 07:17:20
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。发布于 2014-11-09 07:35:50
这是你怎么做的
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;https://stackoverflow.com/questions/26825786
复制相似问题