JavaScript array index 'undefined' in Inte

2020-03-26 05:30发布

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?

4条回答
女痞
2楼-- · 2020-03-26 06:06

If you use the following code, try to increase TimeOut value to maximum...

window.setTimeOut('Your Js function(), 150)

Now, it increase to

window.setTimeOut('Your Js function(), 2000)
查看更多
放我归山
3楼-- · 2020-03-26 06:07

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>
查看更多
Viruses.
4楼-- · 2020-03-26 06:08

It's console the problem here. This object does not exist in IE Javascript engine.

If you do this it works in both

<script>
function main()
{
    var x = "hello world", result = "";
    for ( var i = 0; i < x.length; ++i )
       result += x[i];
    document.write(result); //it prints "hello world" on page
}
main();
</script>

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)
查看更多
Root(大扎)
5楼-- · 2020-03-26 06:09

Older versions of IE don't support the array notation (string[x]) to access strings, use: charAt() instead.

<script>
    function main() {
        var x = "hello world";
        for ( var i = 0; i < x.length; ++i ) {
            console.log( x.charAt(i) );
        }
    }
    main();
</script>

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)

<script>
    (function main() {
        var x = "hello world";
        for ( var i = 0; i < x.length; ++i ) {
            console.log( x.charAt(i) );
        }
    }());
</script>

Unless you have to run it from somewhere else also, of course.

查看更多
登录 后发表回答