我一直认为,如果您想访问名为 str
的字符串中的第 n 个字符,那么您必须执行类似 str.charAt(n)
的操作.今天我正在制作一个小的虚拟测试页面,我错误地使用 str[n]
访问了它,令我惊讶的是,它返回了字符串的第 n 个字符。我抛出了这个专门构建的小页面来展示这种(对我来说)意想不到的行为:
<!doctype html>
<html>
<body>
<script>
var str = "ABCDEFGH";
if (str[4] === str.charAt(4)) alert("strings can be indexed directly as if they're arrays");
var str2 = new String("ABCDEFGH");
if (str2[4] === str2.charAt(4)) alert("even if they're declared as object type String");
</script>
</body>
</html>
它并不总是这样,是吗?
最佳答案
There are two ways to access an individual character in a string. The first is the
charAt
method:return 'cat'.charAt(1); // returns "a"
The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:
return 'cat'[1]; // returns "a"
Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String
关于JavaScript:我们是否总能像索引数组一样索引字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14921011/