According to the MDN JS Doc, the charAt method takes in an integer and returns an the character at the index. And
If the index you supply is out of range, JavaScript returns an empty string.
What I found is that it also takes string as an argument and the return value is intriguing.
The example code: http://jsfiddle.net/yangchenyun/4m3ZW/
var s = 'hey, have fun here.'
>>undefined
s.charAt(2);
>>"y" //works correct
s.charAt('2');
>>"y" //This works too
s.charAt('a');
>>"h" //This is intriguing
Does anyone have a clue how this happens?
The algorithm is described in Section 15.5.4.4 in the specification. There you will see (
posbeing the parameter passed tocharAt):ToIntegeris described in Section 9.4:'a'is not a numerical string and hence cannot be converted to a number, soToNumberwill returnNaN(see Section 9.3.1) which then results in0.On the other side, if you pass a valid numerical string, such as
'2',ToNumberwill convert it to the corresponding number,2.Bottom line:
s.charAt('a')is the same ass.charAt(0), because'a'cannot be converted to an integer.