Javascript string.charAt(x) 还是 string[x]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5943726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
string.charAt(x) or string[x]?
提问by Blender
Is there any reason I should use string.charAt(x)
instead of the bracket notation string[x]
?
有什么理由我应该使用string.charAt(x)
而不是括号表示法string[x]
吗?
采纳答案by Brian Webster
Bracket notation now works on all major browsers, except for IE7 and below.
括号表示法现在适用于所有主要浏览器,IE7 及以下版本除外。
// 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):
由于以下原因(来源),使用方括号曾经是一个坏主意:
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.
此表示法在 IE7 中不起作用。第一个代码片段将在 IE7 中返回 undefined。如果您碰巧在整个代码中对字符串使用括号表示法,并且想要迁移到
.charAt(pos)
,这将是一个真正的痛苦:括号在您的代码中使用,并且没有简单的方法来检测它是用于字符串还是数组/目的。您无法使用此表示法设置字符。由于没有任何形式的警告,这确实令人困惑和沮丧。如果您正在使用该
.charAt(pos)
功能,您就不会想要这样做。
回答by Matt Ball
From MDN:
来自MDN:
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".
有两种方法可以访问字符串中的单个字符。第一个是
charAt
方法,ECMAScript 3 的一部分:return 'cat'.charAt(1); // returns "a"
另一种方法是将字符串视为类数组对象,其中每个单独的字符对应一个数字索引。自第一个版本以来,大多数浏览器都支持此功能,但 IE 除外。它在 ECMAScript 5 中被标准化:
return 'cat'[1]; // returns "a"
第二种方式需要 ECMAScript 5 支持(在一些旧浏览器中不支持)。
在这两种情况下,尝试更改单个字符都不起作用,因为字符串是不可变的,即它们的属性既不是“可写的”也不是“可配置的”。
str.charAt(i)
is better from a compatibility perspective if IE6/IE7 compatibility is required.str[i]
is more modern and works in IE8+ and all other browsers (all Edge/Firefox/Chrome, Safari 2+, all iOS/Android).
str.charAt(i)
如果需要 IE6/IE7 兼容性,从兼容性的角度来看更好。str[i]
更现代,适用于 IE8+ 和所有其他浏览器(所有 Edge/Firefox/Chrome、Safari 2+、所有 iOS/Android)。
回答by MarkG
回答by CharithJ
String.charAt() is the original standard and works in all the browsers. In IE 8+ and other browsers, you may use bracket notation to access characters but IE 7 and below did not support it.
String.charAt() 是原始标准,适用于所有浏览器。在 IE 8+ 和其他浏览器中,您可以使用括号表示法来访问字符,但 IE 7 及以下版本不支持它。
If somebody really wants to use bracket notation in IE 7, it's wise to convert the string to an array using str.split('')
and then use it as an array, compatible with any browser.
如果有人真的想在 IE 7 中使用括号表示法,明智的做法是将字符串转换为数组str.split('')
,然后将其用作数组,与任何浏览器兼容。
var testString = "Hello";
var charArr = testString.split("");
charArr[1]; // "e"
回答by Arman McHitarian
Very interesting outcome when you test the string index accessor vs the charAt()
method. Seems Chrome is the only browser that likes charAt
more.
当您测试字符串索引访问器与charAt()
方法时,结果非常有趣。似乎 Chrome 是唯一喜欢charAt
更多的浏览器。
回答by Donald Duck
There is a difference when you try to access an index which is out of bounds or not an integer.
当您尝试访问超出范围或不是整数的索引时,会有所不同。
string[x]
returns the character at the x
th position in string
if x
is an integer between 0 and string.length-1
, and returns undefined
otherwise.
string[x]
返回if 中x
第 th 位置的字符是 0 和 之间的整数,否则返回。string
x
string.length-1
undefined
string.charAt(x)
converts x
to an integer using the process explained here(which basically rounds x
down if x
is a non-integer number and returns 0 if parseInt(x)
is NaN
) and then returns the character at the that position if the integer is between 0 and string.length-1
, and returns an empty string otherwise.
string.charAt(x)
转换x
使用过程中的整数解释这里(其基本上舍x
下来,如果x
是一个非整数,并返回0,如果parseInt(x)
是NaN
),然后,如果此整数为0之间,并在返回该位置的字符string.length-1
,并且返回一个空字符串,否则.
Here are some examples:
这里有些例子:
"Hello"[313] //undefined
"Hello".charAt(313) //"", 313 is out of bounds
"Hello"[3.14] //undefined
"Hello".charAt(3.14) //'l', rounds 3.14 down to 3
"Hello"[true] //undefined
"Hello".charAt(true) //'e', converts true to the integer 1
"Hello"["World"] //undefined
"Hello".charAt("World") //'H', "World" evaluates to NaN, which gets converted to 0
"Hello"[Infinity] //undefined
"Hello".charAt(Infinity) //"", Infinity is out of bounds
Another difference is that assigning to string[x]
does nothing (which can be confusing) and assigning to string.charAt(x)
is an error (as expected):
另一个区别是分配给string[x]
什么都不做(这可能会令人困惑)而分配给string.charAt(x)
是一个错误(如预期的那样):
var str = "Hello";
str[0] = 'Y';
console.log(str); //Still "Hello", the above assignment did nothing
str.charAt(0) = 'Y'; //Error, invalid left-hand side in assignment
The reason why assigning to string[x]
doesn't work is because Javascript strings are immutable.
分配给string[x]
不起作用的原因是因为Javascript 字符串是不可变的。