0

我正在尝试使用 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();​
4

1 回答 1

0

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"]
于 2012-08-04T02:01:17.403 回答