我正在学习 javascript 字符串方法 here 。
在提取字符串字符部分下,它说:
有 2 种安全方法用于提取字符串字符:
charAt(位置)
charCodeAt(位置)
这里的问题是:
- 为什么这些方法被称为安全?
- 这些方法可以防止什么?
最佳答案
有两种方法可以从字符串中访问字符。
// 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
被认为是安全的。
速度测试: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
关于javascript - 为什么 charAt() 和 charCodeAt() 被称为安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34305646/