JavaScript 字符串 at() 方法
字符串 at() 方法
JavaScript 字符串 at() 方法用于从字符串的指定位置检索单个字符。它接受一个整数值,并返回一个包含单个 UTF-16 代码单元(用于 JavaScript 字符串 的编码系统)的新字符串。
如果未找到给定的整数值(索引),则返回 'undefined'。
JavaScript 中的 at() 和 charAt() 方法 非常相似。但是,它们之间存在以下关键区别:-
at()是 JavaScript 中较新的函数,而charAt()则已存在多年。at()方法更简洁,因为它可以读取和使用负索引,而charAt()则不支持负索引,并且在给定负索引时返回空字符串。
语法
以下是 JavaScript 字符串 at() 方法的语法:-
at(index)
参数
此方法接受一个名为 index 的参数,该参数如下所述 -
-
index- 要返回的字符串字符的索引(或位置)。
返回值
此方法返回一个包含单个字符的新字符串。
示例 1
检索给定字符串的第一个字符。
在给定的示例中,我们使用 at() 方法检索给定字符串"Tutorials Point"的第一个字符。由于索引从 0 开始并以 str.length-1 结束,因此我们将索引值传递为 0 以检索第一个字符。
<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
const str = "Tutorials Point";
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>
输出
上述程序返回字符串"Tutorials Point"的第一个字符,格式为:
String: Tutorials Point Index: 0 The first character of string 'Tutorials Point' is: T
示例 2
通过将负索引传递给 at() 方法,检索给定字符串的最后一个字符。
以下是 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"的最后一个字符,格式为:-
String: 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() 方法之间的区别 -
String: JavaScript The second last element using at(-2) method: p The second last element using charAt(str.length-2) method: p

