string.charAt(x) or string[x]?

后端 未结 6 1268
心在旅途
心在旅途 2020-11-22 04:18

Is there any reason I should use string.charAt(x) instead of the bracket notation string[x]?

6条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 05:00

    They can give different results in edge cases.

    'hello'[NaN] // undefined
    'hello'.charAt(NaN) // 'h'
    
    'hello'[true] //undefined
    'hello'.charAt(true) // 'e'
    

    The charAt function depends on how the index is converted to a Number in the spec.

提交回复
热议问题