而循环切片

时间:2012-08-04 01:34:23

标签: javascript while-loop

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

1 个答案:

答案 0 :(得分: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"]