JavaScript的:对不起,我们总是能够索引到的字符串,就像是一个数组? [英] JavaScript: Have we always been able to index into a string like it's an array?
问题描述
我一直认为,如果你要访问一个名为 STR
字符串,那么你必须做一些像 str中第n个字符.charAt(N)
。今天,我正在一点点假人的测试页和误,我与海峡[N]
让我吃惊访问它,它返回我的字符串的第n个字符。我扔了这小目的建造页面出现此意外的(对我)的行为:
I've always thought that if you want to access the nth character in a string called str
, then you have to do something like str.charAt(n)
. Today I was making a little dummy test page and by mistake, I accessed it with str[n]
and to my surprise, it returned me the nth character of the string. I threw up this little purpose built page to exhibit this unexpected (to me) behaviour:
<!doctype html>
<html>
<body>
<script>
var str = "ABCDEFGH";
if (str[4] === str.charAt(4)) alert("strings can be indexed directly as if they're arrays");
var str2 = new String("ABCDEFGH");
if (str2[4] === str2.charAt(4)) alert("even if they're declared as object type String");
</script>
</body>
</html>
这是不是总是这样,对吧?
It wasn't always like this, was it?
推荐答案
没有,那是不可能的。
如果你在一个足够老浏览器中运行code,IE 7例如,将无法访问字符串这样。在这些较旧的发动机,你必须使用 .charAt(指数)
代替。
If you run your code in an old enough browser, IE 7 for example, it won't be able to access the string like that. On those older engines, you'd have to use .charAt(index)
instead.
这篇关于JavaScript的:对不起,我们总是能够索引到的字符串,就像是一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!