JavaScript 字符串 charAt() 方法
JavaScript 字符串 charAt() 方法返回一个新字符串,该字符串包含原始字符串中指定索引处的单个字符。索引是字符在字符串中的位置,从 0 表示第一个字符,到 n-1 表示最后一个字符,其中 n 表示字符串的长度。
注意 - 如果给定的索引值超出 0 到 str.length-1 的范围,则此方法返回空字符串。它还将空格视为有效字符,并将其包含在输出中。
语法
以下是 JavaScript 字符串 charAt() 方法的语法 -
charAt(index)
参数
此方法接受一个名为"index"的可选参数,其解释如下 -
- index - 字符的索引(位置)。
返回值
此方法返回指定索引处的字符。
示例 1
当我们省略 index 参数时,charAt() 方法会假定其 index 参数的默认值为 0,并且返回给定字符串"Tutorials Point"中的第一个字符"T"。
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
const str = "Tutorials Point";
document.write("str = ", str);
document.write("<br>str.charAt() returns = ", str.charAt());
</script>
</body>
</html>
输出
上述程序返回默认索引 (0) 字符"T"。
str = Tutorials Point str.charAt() returns = T
示例 2
如果我们将索引值 6 传递给此方法,它将返回一个在指定索引处包含单个字符的新字符串。
以下是 JavaScript 字符串 charAt() 方法的另一个示例。在这里,我们使用此方法检索给定字符串"Hello World"中在指定索引 6 处包含单个字符的字符串。
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
const str = "Hello World";
document.write("str = ", str);
let index = 6;
document.write("<br>index = ", index);
document.write("<br>The character at index ", index ," is = ", str.charAt(index));
</script>
</body>
</html>
输出
执行上述程序后,返回指定索引 6 处的字符"W"。
str = Hello World index = 6 The character at index 6 is = W
示例 3
当索引参数不在 0 和 str.length-1 之间时,此方法返回一个空字符串。
我们可以通过执行以下程序来验证,如果索引参数超出 0-str.length-1 的范围,charAt() 方法是否会返回空字符串。
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
const str = "JavaScript";
document.write("str = ", str);
document.write("<br>str.length = ", str.length);
let index = 20;
document.write("<br>index = ", index);
document.write("<br>The character at index ", index , " is = ", str.charAt(index));
</script>
</body>
</html>
输出
对于超出范围的索引值,它将返回一个空字符串,如下所示:
str = JavaScript str.length = 10 index = 20 The character at index 20 is =
示例 4
此示例演示了 charAt() 方法的实时用法。它统计给定字符串"Welcome to Tutorials Point"中的空格和单词数量。
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script>
const str = "Welcome to Tutorials Point";
document.write("Given string = ", str);
let spaces = 0;
for(let i = 0; i<str.length; i++){
if(str.charAt(i) == ' '){
spaces = spaces + 1;
}
}
document.write("<br>Number of spaces = ", spaces);
document.write("<br>Number of words = ", spaces + 1);
</script>
</body>
</html>
输出
上述程序统计并返回字符串中空格和单词的数量。
Given string = Welcome to Tutorials Point Number of spaces = 3 Number of words = 4

