我正在嘗試使用while循環來切出一大塊文本,使每個片段長度不超過995個字符並以句點結尾。我幾乎得到它的工作,除非最後一塊從未被推入陣列。這是爲什麼?while循環片
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();
while循環條件應該是'currentLoc
Bergi
2012-08-04 01:58:28
在沒有句點的情況下,如果字符串長度超過995個字符,你希望它做什麼? – 2012-08-04 02:05:12