Dennis G
Dennis G

Reputation: 21788

IE7 Javascript and using string as an array

Weird behavior and I'm just posting this question to see if anyone knows the reason for this or whether my code is just plain wrong:

string text = "~"; //yip, let's take some weird character
alert(text[0]);
//all major browsers output "~"
//IE6 & 7: undefined
alert(text.charAt(0));
//works in all browsers

Now my question is: Is using a text as an array not supported in IE7, is the code wrong in general and is it OK to use .charAt(i) instead of string[i]?

PS: There is some guy who answered his own question regarding exactly this. My question remains: Where is this documented? Is this a regular IE "bug"?

Upvotes: 6

Views: 2827

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

Accessing string array-like is not standard in ECMAScript 3:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#section_5

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

What you do is split the string:

var textChars = text.split('');
alert(textChars[0]);

Upvotes: 8

Related Questions