javascript - string.charAt(x) 还是 string[x]?

标签 javascript string

有什么理由我应该使用 string.charAt(x) 而不是括号表示法 string[x]

最佳答案

括号表示法现在适用于所有主流浏览器,IE7 及以下版本除外。

// Bracket Notation
"Test String1"[6]

// charAt 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.

关于javascript - string.charAt(x) 还是 string[x]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5943726/

相关文章:

c - 读取 XML 文件并使用 C 打印标签

javascript - 如果我让所有数据对所有 Controller 可用,我会遇到什么问题?

javascript - Extjs - formPanel 上的 isValid()

javascript - 功能策略 : Skipping unsupported feature name “picture-in-picture” / “autoplay” / “encrypted-media”

c++ - 包含 std::string 常量的类

ios - 无法从 UITextField - Swift - iOS 获取文本

python - 从系列和字符串创建数据框

javascript - append li 时,它不会成为 ul "for real"的一部分吗?

javascript - Facebook 喜欢 facebook 状态的按钮

java - Java中Varchar中英文混合的字符串长度