0

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!

Cerulean
  • 5,543
  • 9
  • 59
  • 111
  • 3
    It works exactly the same. Your code in fact executes exactly the same for me with `string[i]`. – fjc Jul 09 '18 at 19:59
  • 1
    This could be a browser difference, technically you should not use the array version. Also please name the variable! string[1] should return 't' This may be of help -> https://stackoverflow.com/questions/5943726/string-charatx-or-stringx – Paul Swetz Jul 09 '18 at 20:00
  • 1
    They work the same for me. Check the output here: http://rextester.com/SPYPQ47289 – Stuti Rastogi Jul 09 '18 at 20:01
  • Thanks to all. I was running it in Node REPL. I'll check it in a browser. And thanks for the suggestions. I actually had read that StackOverflow article but had thought perhaps it was OK to use the array form now, as it is part of ECMA 5. – Cerulean Jul 09 '18 at 21:15

0 Answers0