Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 613
Dennis G Avatar asked Dec 06 '11 08:12

Dennis G


1 Answers

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]);
like image 178
Didier Ghys Avatar answered Sep 21 '22 23:09

Didier Ghys