我正在尝试从一个长字符串中计算每个句子中的单词数。我得到的只是句子的数量。我在 C# 和 Ruby 中找到了一些解决方案,但它们不适合我:-))
我对java脚本真的很陌生。非常感谢任何帮助。代码如下:
输出如下:
字数:1 已发送:1 字数:0 已发送:2 字数:1 已发送:3 字数:1 已发送:4 字数:1 已发送:5 字数:1 已发送:6
单词计数器没有增加!最有可能的是很简单的事情。 预先感谢您。
var text1 = $('#textarea1').val();
var gaps = [];
var wordsC = 0;
var wordsTot = 0;
var tempC = 0;
var sents = text1.split('.');
for (var elem in sents)
{
tempC += 1;
wordsC = elem.split(" ").length;
wordsTot += wordsC;
if (tempC == 2) {
wordsC -= 1;
wordsTot -= 1;
}
document.write("<br />Words: " + wordsC + " |in sent: " + tempC + " sent");
};
document.write("<br />words total : " + wordsTot + "<br />" );
最佳答案
您不应该使用 for...in
枚举数组。 text1.split('.');
正在生成一个数组,您正尝试使用 for...in
枚举该数组。 for...in
每次迭代时的 elem
值是字符串形式的数组索引之一(第一次迭代为“0”,第一次迭代为“1”)在第二个,依此类推)。您甚至最终会得到一些数组原型(prototype)方法和原型(prototype)更改中的其他内容。
对于 ES6 之前的环境,请尝试:
for (var i = 0; i < sents.length; i++)
{
tempC += 1;
wordsC = sents[i].split(" ").length;
wordsTot += wordsC;
if (tempC == 2) {
wordsC -= 1;
wordsTot -= 1;
}
document.write("<br />Words: " + wordsC + " |in sent: " + tempC + " sent");
}
ES6 引入了一个 for...of
结构来完成你想要做的事情:
for (let elem of sents)
{
tempC += 1;
wordsC = elem.split(" ").length;
wordsTot += wordsC;
if (tempC == 2) {
wordsC -= 1;
wordsTot -= 1;
}
document.write("<br />Words: " + wordsC + " |in sent: " + tempC + " sent");
};
关于javascript - 计算长字符串中每个句子的单词,jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531830/