我写了一个简短的函数将一个字符串分成单词数组(使用循环-这是一种练习,我不认为这是漂亮的代码)。当我使用String.charAt()
访问字符时,它可以正常工作,但是当我使用string[i]
时,它不能工作。这些不应该给出相同的结果吗?
"use strict"
function whitespace(ch) {
return (ch == ' ') || (ch == '\t') || (ch == '\n');
}
function splitToWords(string) {
var words = [];
var wordStart = 0;
var inWord = false;
var isWhitespace;
for (var i = 0; i <= string.length; i++) {
//this works fine
isWhitespace = whitespace(string.charAt(i));
// but this doesn't -- causes the final test (below) to fail
// isWhitespace = whitespace(string[i]);
if (inWord && isWhitespace) {
words.push(string.slice(wordStart, i));
inWord = false;
} else if (!inWord && !isWhitespace) {
wordStart = i;
inWord = true;
}
}
if (inWord) words.push(string.slice(wordStart, i));
return words;
}
当我使用String.charAt()
时,此测试通过,但是对字符串的索引访问失败
var words = splitToWords(' ');
console.log(words.length === 0); // => true
两种访问模式都不会给出相同的结果吗?多谢您指出我的错误!