本节练习
编写一个函数,实现以下功能:计算出一个字符串共有多少个单词组成。
function countWords(message){
// wirte your code here
}
countWords('Good morning, I love JavaScript.'); // should return 5
代码如下:
function countWords(message)
{
var array=countWords.split(" ");
var y ={};
for(var i=0;i<array.length;i++)
{
var countWords =array[i];
if(!y[countWords])
{
y[countWords]=1;
}
else
{
y[countWords]++;
}
}
}
countWords('Good morning, I love JavaScript.'); // should return 5