Internet Explorer中的JavaScript数组索引“未定义"

问题描述:

以下脚本会为字符串中的每个字符将 undefined 打印到控制台,但在Chrome中可以正常工作.

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?

某些浏览器(但并非所有浏览器)都支持[]:

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

类似数组的字符访问(上面的第二种方式)不属于 ECMAScript3.这是JavaScript和ECMAScript 5功能.

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

为获得最大兼容性,请使用 String.charAt() 代替:

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>