I’ve been playing around with CoffeeScript, and found myself needing to loop over the characters (and indexes) in a string. So I tried a simple CoffeeScript
for char, index in line # ...
I ran it, and it worked, even in IE, so I assumed that CoffeeScript was doing whatever magical syntax was required to make it work everywhere.
Later I found out I was wrong. CoffeeScript was generating the syntax that works with arrays —
list[index] — and that syntax only happens to sometimes work with strings. It works consistently in Chrome, and FireFox, and Opera. It even works in IE… but only if you have an HTML5 doctype.
<!DOCTYPE html> <script> document.write('abc'); </script>
The above HTML page works fine in IE9, outputting
b as expected. But if you remove the
<!DOCTYPE html> line, IE outputs
Frame, even the doctype won’t save you — it always outputs
When I went back and looked through the CoffeeScript documentation, sure enough, nowhere do they actually say that
for loops can be used to iterate through the characters in a string. The fact that it ever works is apparently an accident, so don’t rely on it.
If you need to loop over the characters in a string,
the right thing is to loop over the indexes and use See update below
for index in [0...line.length] char = line.charAt index # ...
Edit: Here’s a better way, suggested by the kind CoffeeScript folks:
for char, index in str.split ''