是否有任何理由我应该使用string. charat (x)而不是括号符号字符串[x]?


当前回答

括号符号现在适用于所有主流浏览器,除了IE7及以下版本。

// Bracket Notation
"Test String1"[6]

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

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

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.

其他回答

当您测试字符串索引访问器与charAt()方法时,会得到非常有趣的结果。看来Chrome是唯一一个更喜欢字符的浏览器。

CharAt vs index 1

图表与索引

图表与指数

String.charAt()是原始标准,适用于所有浏览器。 在IE 8+和其他浏览器中,您可以使用括号符号来访问字符,但IE 7及以下版本不支持。

如果有人真的想在IE 7中使用括号表示法,明智的做法是使用str.split(")将字符串转换为数组,然后将其作为数组使用,与任何浏览器兼容。

var testString = "Hello"; 
var charArr = testString.split("");
charArr[1]; // "e"

中数:

There are two ways to access an individual character in a string. The first is the charAt method, part of ECMAScript 3: return 'cat'.charAt(1); // returns "a" The other way is to treat the string as an array-like object, where each individual characters correspond to a numerical index. This has been supported by most browsers since their first version, except for IE. It was standardised in ECMAScript 5: return 'cat'[1]; // returns "a" The second way requires ECMAScript 5 support (and not supported in some older browsers). In both cases, attempting to change an individual character won't work, as strings are immutable, i.e., their properties are neither neither "writable" nor "configurable".

如果需要IE6/IE7兼容性,从兼容性角度来看str.charAt(i)更好。 str[i]更现代,适用于IE8+和所有其他浏览器(所有Edge/Firefox/Chrome, Safari 2+,所有iOS/Android)。

括号符号现在适用于所有主流浏览器,除了IE7及以下版本。

// Bracket Notation
"Test String1"[6]

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

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

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.

它们在边缘情况下可以给出不同的结果。

'hello'[NaN] // undefined
'hello'.charAt(NaN) // 'h'

'hello'[true] //undefined
'hello'.charAt(true) // 'e'

charAt函数取决于如何将索引转换为规范中的数字。