JavaScript String charCodeAt() 方法在指定索引处返回一个介于 0 到 65535 之间的整数。该整数值被视为单个字符的 Unicode。索引从 0 开始,以 str.length-1 结束。
如果 index 参数值不在 0 到 str.length-1 的范围内,则返回 'NaN'。
语法
以下是 JavaScript String charCodeAt() 方法的语法 -
charCodeAt(index)
参数
此方法采用一个名为 'index' 的可选参数,下面将解释 -
- index − 字符的索引(位置)。
返回值
此方法返回指定索引处字符的 Unicode。
示例 1
当我们省略 index 参数时,此方法假定其 index 参数默认值为 0,并返回给定字符串 “Qikepu” 中第一个字符 'Q' 的 Unicode。
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
const str = "Qikepu";
document.write("String value = ", str);
document.write("<br>The character code ", str.charCodeAt(), " is equal to ", str.charAt());
</script>
</body>
</html>
输出
上面的程序将字符 'Q' 的 Unicode 返回为 81。
String value = Qikepu
The character code 81 is equal to T
The character code 81 is equal to T
示例 2
如果我们将 index 值作为 6 传递给此方法,它将返回指定索引处字符的 Unicode。
以下是 JavaScript String charCodeAt() 方法的另一个示例。在这里,我们使用此方法检索给定字符串 “Hello World” 中指定索引 6 处字符的 Unicode。
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
const str = "Hello World";
document.write("String value = ", str);
let index = 6;
document.write("<br>Index value = ", index);
document.write("<br>The character at ", index, "th position is: ", str.charAt(index));
document.write("<br>The Unicode of a character '", str.charAt(index), "' is: ", str.charCodeAt(index));
</script>
</body>
</html>
输出
执行上述程序后,它将返回字符 'W' 的 Unicode 87。
String value = Hello World
Index value = 6
The character at 6th position is: W
The Unicode of a character 'W' is: 87
Index value = 6
The character at 6th position is: W
The Unicode of a character 'W' is: 87
示例 3
当 index 参数不在 0 到 str.length-1 之间时,该方法返回 'NaN'。
我们可以通过执行下面的程序来验证上述事实陈述,即如果 index 参数超出 0 到 str.length-1 的范围,则 charCodeAt() 方法返回 'NaN'。
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
const str = "JavaScript";
document.write("String value = ", str);
let index = 15;
document.write("<br>Index value = ", index);
document.write("<br>The character at ", index, "th position is: ", str.charAt(index));
document.write("<br>The Unicode of a character '", str.charAt(index), "' is: ", str.charCodeAt(50));
</script>
</body>
</html>
输出
此方法将返回 'NaN',因为索引值超出范围。
String value = JavaScript
Index value = 15
The character at 15th position is:
The Unicode of a character '' is: NaN
Index value = 15
The character at 15th position is:
The Unicode of a character '' is: NaN