Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array index 'undefined' in Internet Explorer

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?


1 Answers

The [] is supported in some browsers but not all:

Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

For maximum compatibility, use String.charAt() instead:

<script>
function main()
{
    var x = "hello world";
    for ( var i = 0; i < x.length; ++i ) {
        console.log( x.charAt(i) );
    }
}
main();
</script>
like image 157
Salman A Avatar answered Sep 04 '26 15:09

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!