ES5-String-charAt

259 阅读1分钟

charAt方法返回指定位置的字符,参数是从0开始编号的位置。

var s = new String('abc');

s.charAt(1) // "b"
s.charAt(s.length - 1) // "c"

这个方法完全可以用数组下标替代。

'abc'.charAt(1) // "b"
'abc'[1] // "b"
  • 需要特别注意的是,字符串是不可变的,如果对字符串的某个索引赋值,不会有任何错误,但是,也没有任何效果:
var s = 'Test';
s[0] = 'X';
alert(s); // s仍然为'Test'

如果参数为负数,或大于等于字符串的长度,charAt返回空字符串

'abc'.charAt(-1) // ""
'abc'.charAt(3) // ""