I wrote a short function to split a string into an array of words (using a loop -- this was an exercise, I don't claim it's pretty code). It works fine when I use String.charAt()
to access a character but doesn't when I use string[i]
. Shouldn't these give the same results?
"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;
}
This test passes when I use String.charAt()
but fails using index access to the string
var words = splitToWords(' ');
console.log(words.length === 0); // => true
Shouldn't the two modes of access give the same result? Thanks for any help in pointing out my error!