Internet Explorer中的JavaScript数组索引“未定义" [英] JavaScript array index 'undefined' in Internet Explorer

查看:87
本文介绍了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>

这篇关于Internet Explorer中的JavaScript数组索引“未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆