为什么 charAt() 和 charCodeAt() 被称为安全的?

Why charAt() and charCodeAt() are called safe?

我正在学习 javascript 字符串方法 here

提取字符串字符 部分下,它说:

提取字符串字符有2种安全方法:

这里的问题是:

有两种方法可以访问字符串中的字符。

// Bracket Notation
"Test String1"[6]

// Real Implementation
"Test String1".charAt(6)

使用括号是个坏主意,原因如下 (Source):

This notation does not work in IE7. The first code snippet will return undefined in IE7. If you happen to use the bracket notation for strings all over your code and you want to migrate to .charAt(pos), this is a real pain: Brackets are used all over your code and there's no easy way to detect if that's for a string or an array/object.

You can't set the character using this notation. As there is no warning of any kind, this is really confusing and frustrating. If you were using the .charAt(pos) function, you would not have been tempted to do it.

此外,它会在 edge cases

中产生意想不到的结果

console.log('hello' [NaN]) // undefined
console.log('hello'.charAt(NaN)) // 'h'

console.log('hello' [true]) //undefined
console.log('hello'.charAt(true)) // 'e'

基本上,这是一种并非所有浏览器都完全实现的快捷方式。

请注意,您无法使用任何一种方法书写字符。但是,使用 .charAt() 函数更容易理解该功能,在大多数语言中,该函数是只读函数。

因此出于兼容性目的,.charAt 被认为是安全的。

Source

速度测试:http://jsperf.com/string-charat-vs-bracket-notation

Testing in Chrome 47.0.2526.80 on Mac OS X 10.10.4
Test    Ops/sec

String charAt
testCharAt("cat", 1);
117,553,733
±1.25%
fastest

String bracket notation
testBracketNotation("cat", 1);
118,251,955
±1.56%
fastest