JavaScript:我们是否总能像索引数组一样索引字符串?

标签 javascript arrays string indexing

我一直认为,如果您想访问名为 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/

相关文章:

php - 如何在 PHP 中使用 * 等式字符串验证括号

javascript - console.log 的级别少 = false 转储?

arrays - 逐个元素构建 Julia 数组的有效方法

c# - 将根 JSON 数组映射到类型的属性。 。网

javascript - 将字符串拆分为数组,但在应用连接时仍保留逗号。 - JavaScript

C - while(*Table[i]) 是什么意思/做什么?

javascript - 在 react-redux 应用程序中导航到不同的路由时删除 redux 状态?

javascript - 具有单个值的 Highcharts 饼图(以 % 表示)

javascript - 在命名空间中没有静态函数的情况下迭代枚举

javascript - 为什么我的方法没有将结果推送到我的阵列?