例如输入"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()并在那里创建一个expectedCount方法并导出它?
我是否将字符串视为数组或对象?对于对象,如何开始将它们分解为单词并迭代计数?
答案 0 :(得分: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"));
此代码应该可以满足您的需求 为了更好地理解代码,我建议你通过数组原型函数和字符串原型函数 为了简单理解我在这里做的事情:
split(" ")
拆分字符串。forEach
方法迭代spitted数组中的所有元素。:?
,用于检查值是否已存在,是否增加1或将其指定为1。答案 1 :(得分:0)
这是你怎么做的
字符-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;