string.charAt()在传递字符串作为参数时如何工作?

ste*_*ang 3 javascript string

根据MDN JS Doc,该charAt方法接受integer并返回索引处的字符.和

如果您提供的索引超出范围,JavaScript将返回一个空字符串.

我发现它也是string一个参数,返回值很有趣.

示例代码: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
Run Code Online (Sandbox Code Playgroud)

有没有人知道这是怎么发生的?

Fel*_*ing 9

该算法在规范的第15.5.4.4节中描述.你会看到(pos作为参数传递给charAt):

(...)
3.让位置为ToInteger(pos).
(......)

ToInteger9.4节中描述:

  1. number是在输入参数上调用ToNumber的结果.
  2. 如果numberNaN,则返回+0.
    (......)

'a'不是数字字符串,因此不能转换为数字,因此ToNumber将返回NaN(参见第9.3.1节),然后产生0.

另一方面,如果你传递一个有效的数字字符串,比如'2',ToNumber将它转换为相应的数字,2.


底线:

s.charAt('a')是一样的s.charAt(0),因为'a'无法转换为整数.