The following script prints undefined to the console for each character in the string, but works correctly in Chrome.
<script>
function main()
{
var x = "hello world";
for ( var i = 0; i < x.length; ++i ) {
console.log( x[i] );
}
}
main();
</script>
Do I have to do something to the array in order to get this to work properly in all browsers?
If you use the following code, try to increase TimeOut value to maximum...
Now, it increase to
The
[]
is supported in some browsers but not all:For maximum compatibility, use
String.charAt()
instead:It's
console
the problem here. This object does not exist in IE Javascript engine.If you do this it works in both
EDIT:
console
object does not exists until IE10 (as correctly noted by Cerbrus, unless you turn on the IE developer tool, in such case it exists also on IE8)[]
to access strings chars can be used in IE8+ (on IE7 it does not work yet)Older versions of IE don't support the array notation (
string[x]
) to access strings, use:charAt()
instead.Also, if you're directly executing your function, you could as well create a self-executing anonymous function (to preserve the scope / not pollute the global namespace)
Unless you have to run it from somewhere else also, of course.