JavaScript String at() 方法用于从指定位置的字符串中检索单个字符。它接受一个整数值,并返回一个包含单个 UTF-16 代码单元(用于 JavaScript 字符串的编码系统)的新字符串。
如果未找到给定的整数值 (index),则返回 'undefined'。
JavaScript 中的 “at()” 和 “charAt()” 方法彼此非常相似。但是,它们之间存在以下主要区别 -
- at() 是 JavaScript 的新成员,而 charAt() 已经存在了更长的时间。
- at() 方法更简洁,因为它可以读取和使用负索引,这与 charAt() 不同,后者不支持负索引,并在给定负索引时返回空字符串。
语法
以下是 JavaScript String at() 方法的语法 -
at(index)
参数
此方法接受一个名为 'index' 的参数,如下所述 -
- index − 要返回的字符串字符的索引(或位置)。
返回值
此方法返回一个包含单个字符的新字符串。
示例 1
检索给定字符串的第一个字符。
在给定的示例中,我们使用 JavaScript String at() 方法来检索给定字符串 “qikepucom” 的第一个字符。由于索引从 0 开始,到 str.length-1 结束,因此我们将索引值作为 0 传递以检索第一个字符。
<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
const str = "qikepucom";
document.write("String: ", str);
const index = 0;
document.write("<br>Index: ", index);
document.write("<br>The first character of string '", str, "' is: ", str.at(index));
</script>
</body>
</html>
输出
上面的程序将字符串 “qikepucom” 的第一个返回为 −
Index: 0
The first character of string 'qikepucom' is: q
示例 2
通过将负索引传递给 at() 方法来检索给定字符串的最后一个字符。
以下是 JavaScript String at() 方法的另一个示例。我们使用此方法检索给定字符串 “Hello World” 的最后一个字符。由于此方法可以使用和读取负索引,因此我们传递索引值 -1 以返回最后一个字符。
<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
const str = "Hello World";
document.write("String: ", str);
const index = -1;
document.write("<br>Index: ", index);
document.write("<br>The last character of string '", str, "' is: ", str.at(index));
</script>
</body>
</html>
输出
执行上述程序后,返回字符串 “Hello World” 的最后一个字符为 −
Index: -1
The last character of string 'Hello World' is: d
示例 3
比较 at() 和 charAt() 方法
在给定的示例中,我们比较了 “at()” 和 “charAt()” 方法,并尝试检索给定字符串 “JavaScript” 的倒数第二个元素。at() 方法处理负索引,因此索引值 -2 返回倒数第二个元素,而 charAt() 方法将索引值作为 str.length-2 返回倒数第二个元素。
<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
const str = "JavaScript";
document.write("String: ", str);
document.write("<br>The second last element using at(-2) method: ", str.at(-2));
document.write("<br>The second last element using charAt(str.length-2) method: ", str.charAt(str.length-2));
</script>
</body>
</html>
输出
以下输出显示了 at() 和 charAt() 方法之间的差异 -
The second last element using at(-2) method: p
The second last element using charAt(str.length-2) method: p