Possible Duplicate:
string.charAt(x) or string[x]?
It seems that "asdf"[0]
produces "a"
. So why would anyone ever type out "asdf".charAt(0)
?
Is that shorter syntax safe to use?
Cross browser compatibility? That's about all I can think of.
Possible Duplicate:
string.charAt(x) or string[x]?
It seems that "asdf"[0]
produces "a"
. So why would anyone ever type out "asdf".charAt(0)
?
Is that shorter syntax safe to use?
Cross browser compatibility? That's about all I can think of.
You can only access strings as arrays in newer browsers. To support older browsers (i.e. IE7) you have to use charAt
.
Related: string.charAt(x) or string[x]?
I think it makes for cleaner, more readable code. If you use
foo.charAt(0)
instead of
foo[0]
(an array index), you make it clear that foo
is a string, not an array. Also, you are less likely to use other array methods that may fail.
Addendum
Because some people aren't clear what I mean, let me say that again: Other array methods may fail when used on a String
.
Try it yourself:
var foo = "This is a string.";
foo.push(" A string is not an array.");
You will get a TypeError.
And for those who may confuse array notation with bracket notation, try the following experiment. Open up your browser's console and enter the following:
foo = {bar:'ass',fub:'tree',mip:0};
Now try to access the first element with bracket notation:
foo['bar']
returns "ass";
foo[0]
returns undefined
.
Cross-browser compatibility is an issue. When I pop open IE9's console and set it to IE7 standards, "a"[0] produces undefined while "a".charAt(0) works as expected.
Most browsers indeed allow you to treat string as an array of chars (just like it works in many other programming languages).
IE, on the other hand, does not. There, you must use "asdf".charAt(0)
.
Now I would say that allowing the []
notation is just an extra option browsers allow you, to make strings behave similar to languages like C, Pascal, etc. However, strings in Javascript are actually not arrays and thus by standard should not work with []
. Strings are built-in classes, so to access their properties you have to use their public methods, like in Java.