我正试图使用while循环来分割一大块文本,这样每一块都不到995个字符长,并以句点结束。我几乎已经完成了它的工作,除了最后一块从未被推入数组。为什么?
function divideByPunctuation() {
var chunkArray = [];
var textHunk = prompt();
var textLength = textHunk.length;
var currentLoc = 0;
var i = 995;
while (currentLoc <= textLength) {
if (textHunk[i] === ".") {
if (i > textLength) {
chunkArray.push(textHunk.slice(currentLoc, textLength));
break;
} else {
chunkArray.push(textHunk.slice(currentLoc, i));
currentLoc += i;
i = currentLoc + 995;
}
} else {
i--
}
}
console.log(chunkArray[0]);
console.log(chunkArray[1]);
console.log(chunkArray[2]);
console.log(chunkArray[3]);
};
divideByPunctuation();
Javascript有一个很好的内置函数来处理这类事情。
a = "Hi there. Here's a test sentence. Here's another one";
a.split(". ");
["Hi there", "Here's a test sentence", "Here's another one"]