Accessing a single character of a string
There are two ways to get a single character of a string.
The first one is to usecharAt
method
> 'hello'.charAt(1) 'e'
The second is to useSubscript index of class arraymethod
> 'hello'[1] 'e'
Let’s talk about each access method in detail.
charAt method
charAt()
Method returns the character at the specified position in the string.
grammar
(index)
parameterindex: 0
arriveString length -1
an integer.
illustrateThe characters in the string are indexed from left to right, and the index value of the first character is0
, the index value of the last character is - 1
。
If specifiedindex
The value exceeds this range, aEmpty string
。
Example
> a = 'abcd' 'abcd' > (4) // index is out of range, returns an empty string'' > (0) 'a'
Subscript indexing method of class array
Because the string haslength
Attributes, and indexable properties0、1、2...
So, so it can be regarded as aClass arrayObject.
The subscript indexing method of class array is to treat a string as a class array object (ECMA5), and each character in it corresponds to a numerical index.
grammar
string[index]
Note, whenindex
When the range is found, returnundefined
.
Example
> a = 'abcd' 'abcd' > a[0] 'a' > a[1] 'b' > a[2] 'c' > a[3] 'd' > a[4] //index is out of range and returns undefined.undefined
Note that using this subscript indexing method of a class array, only characters can be accessed but not deleted or added, because the corresponding attributes are not readable or writable, after all, a class array is not an array.
Comparison of the two methods
Similarities
- They are all single characters that get a certain position in the string.
- All indexes are from
0
start.
Differences
usecharAt(index)
The way,index
If it is out of range, aEmpty string
。
usestring[index]
The way,index
If it is out of range, it will returnundefined
。
It can be summarized as a compatibility issue.
charAt
yesES3
Method,string[index]
yesES5
method. socharAt(index)
It has strong compatibility and can be used normally under IE6~8.string[index]
The method will return under IE6~8undefined
, that is, IE6~8 is incompatible with this method and can only be used for IE8+.
usestring[index]
There is another inconvenience, that is, it is not easy to distinguish whether an array element or a string is accessed, and it may make people mistakenly think that it is writable.
The above is the detailed content of the single character access method of JavaScript string. For more information about JavaScript access to single characters, please pay attention to my other related articles!