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

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

本文关键字:被称为 安全 charCodeAt 为什么 charAt      更新时间:2023-09-26

我在这里学习了javascript字符串方法。

提取字符串部分,它说:

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

  • charAt(position)
  • charCodeAt(position)

这里的问题是:

  • 为什么这些方法被称为safe
  • 这些方法有哪些保护作用

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

// Bracket Notation
"Test String1"[6]
// Real Implementation
"Test String1".charAt(6)

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

此表示法在IE7中不起作用。第一个代码片段将返回IE7中未定义。如果你碰巧使用字符串的括号表示法all而您想要迁移对于.charAt(pos)来说,这是一个真正的痛苦:括号在你的代码中随处可见没有简单的方法来检测那是一根绳子或一根数组/对象。

不能使用此符号设置字符因为没有警告不管怎样,这真的很令人困惑令人沮丧。如果您使用.charAt(pos)函数,您不会

此外,在边缘情况下,它可能会产生意想不到的结果

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