string.charAt(x) 还是 string[x]? [英] string.charAt(x) or string[x]?

查看:23
本文介绍了string.charAt(x) 还是 string[x]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any reason I should use string.charAt(x) instead of the bracket notation string[x]?

推荐答案

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

Bracket notation now works on all major browsers, except for IE7 and below.

// Bracket Notation
"Test String1"[6]

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

由于这些原因(来源):

It used to be a bad idea to use brackets, for these reasons (Source):

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

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.

您不能使用此符号设置字符.因为没有警告任何种类,这真的很令人困惑和令人沮丧.如果您使用的是.charAt(pos) 函数,你不会已经很想这样做了.

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.

这篇关于string.charAt(x) 还是 string[x]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆