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

标签 javascript string char charat

我正在学习 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 被认为是安全的。

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

关于javascript - 为什么 charAt() 和 charCodeAt() 被称为安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34305646/

相关文章:

javascript 继承和唯一实例

javascript - 如何搜索包含数组中所有字母的单词?

javascript - 删除最后一个特殊字符之后的所有字符javascript

c# - 读取用户的两个输入

c++ - 从 int 到 char* 没有字符串,和 fstream 不方便

c++ - 为什么两个声明的 char* 变量获得相同的地址?

javascript - 第一次使用 AJAX,通过 AJAX 进行 JSON 循环,数据分布在多个页面上?

Ruby - 匹配字符串中的所有模式

c - 在C中读取一行未知格式

c - 关于 char 的通用指针和严格别名