Is there any reason I should use string.charAt(x)
instead of the bracket notation string[x]
?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- how to split a list into a given number of sub-lis
From MDN:
str.charAt(i)
is better from a compatibility perspective if IE6/IE7 compatibility is required.str[i]
is more modern and works in IE8+ and all other browsers (all Edge/Firefox/Chrome, Safari 2+, all iOS/Android).Very interesting outcome when you test the string index accessor vs the
charAt()
method. Seems Chrome is the only browser that likescharAt
more.CharAt vs index 1
ChartAt vs index 2
ChartAt vs index 3
String.charAt() is the original standard and works in all the browsers. In IE 8+ and other browsers, you may use bracket notation to access characters but IE 7 and below did not support it.
If somebody really wants to use bracket notation in IE 7, it's wise to convert the string to an array using
str.split('')
and then use it as an array, compatible with any browser.They can give different results in edge cases.
The charAt function depends on how the index is converted to a Number in the spec.
It is a bad idea to use brackets, for these reasons (Source):
Basically, it's a shortcut notation that is not fully implemented across all browsers.
Note, you are not able to write characters using either method. However, that functionality is a bit easier to understand with the
.charAt()
function which, in most languages, is a read-only function.