Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript while循环切片_Javascript_While Loop - Fatal编程技术网

Javascript while循环切片

Javascript while循环切片,javascript,while-loop,Javascript,While Loop,我正在尝试使用while循环来分割一大块文本,这样每个文本长度都不超过995个字符,并且以句号结尾。我几乎让它工作了,除了最后一块永远不会被推入数组。为什么呢 function divideByPunctuation() { var chunkArray = []; var textHunk = prompt(); var textLength = textHunk.length; var currentLoc = 0; var i = 995;

我正在尝试使用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();​
函数除以标点(){
var chunkArray=[];
var textHunk=prompt();
var textLength=textHunk.length;
var currentLoc=0;
var i=995;
while(currentloctextlength){
push(textHunk.slice(currentLoc,textLength));
打破
}否则{
push(textHunk.slice(currentLoc,i));
currentLoc+=i;
i=当前位置+995;
}
}否则{
我--
}
}
log(chunkArray[0]);
log(chunkArray[1]);
log(chunkArray[2]);
log(chunkArray[3]);
};
除以标点符号();​

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"]

while循环条件应为
currentLoc
。此外,您可以使用
.charAt(i)
代替古代IE不支持的括号表示法。如果字符串长度超过995个字符且没有句点,您希望它做什么?我需要将其拆分为尽可能接近995个字符的块,因此.split()无法帮助我哪一个约束获胜?如果有一个句子长度超过995个字符怎么办?必须小于995个字符,无论该句子是否更长。并不是说有很多1000字的句子