html:
我正在做以下事情:
var words = $("#input-content > p").map(function() {
return $.text(this);
}).get().join(" ");
哪些输出:
"one two three four "
我不明白为什么要这样做:
words.split(" ").length
当只有 4
个单词时输出 5
。
这是为什么呢?如何解决?
最佳答案
String "one two three four "
有一个尾随空格,它会在结果数组的末尾添加一个额外的空字符串,即 ["one", "two", "三”、“四”、“”]
。
为了解决这个问题,考虑使用 trim 功能,比如$.trim()
在 jQuery 中。
关于javascript - 为什么这个简单的计数器要计算一个额外的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108161/