function countTheWords() {
var word = "";
var num;
num = num + 1;
如何为此添加计数器?我试着计算一句话中有多少单词。 下周我有一个测试,我正在学习,我坚持这个。 我知道我的错误,所以请指导我如何计算一个句子中的单词数量。
do {
word = prompt("Enter a sentence one word at a time. Enter exit to finish your sentence.");
word = word + 1;
}while(word != "exit");
document.write("There are: " + word + " words in your sentence");
}
答案 0 :(得分:0)
要测试句子中有多少单词,您可以执行以下操作:
function wordCount(str){
return str.match(/\s/g).length+1;
}
在实际操作中,您不会使用提示或警报,但这也可能有所帮助:
var sen = prompt('Please enter a sentence.');
alert('There are '+wordCount(sen)+' words in your sentence!');
答案 1 :(得分:0)
您可以根据单词分隔符进行拆分,例如“”和新行。
一个例子:
var str = "sample sentence"; // or var str=prompt("Enter a sentence")
var x = str.split(" "); // use newline or any separator if reqd
document.write(x.length)
答案 2 :(得分:0)
解决此问题的一种方法是使用正则表达式。对于输入的每个单词,只需执行以下操作检查单词exit
:
/exit/.test(word);
这将返回您可以测试的boolean
值。
以下是更新后的代码:
var wordCount = 0;
do {
word = prompt("Enter a sentence one word at a time. Enter exit to finish your sentence.");
wordCount++;
}while(/exit/.test(word) === false);
document.write("There are: " + wordCount + " words in your sentence");
阅读:Regular Expressions - JavaScript | MDN
您可以使用数组来计算单词:
var sentence = "This is a sentence.";
var wordCount = sentence.split(' ').length;
console.log(wordCount); // check your browser's Javascript console to see the count
答案 3 :(得分:0)
你可以使用类似的东西:
function wordCounter(word){
return word.split(' ').length
}
答案 4 :(得分:0)
你试过了吗?
function countWords(sentence) {
//Creates an array of all of the words and gets the array's length
return sentence.split(" ").length;
}
alert(countWords("A very simple function can save lots of time")); // 9