JavaScript 字符串 charCodeAt() 方法
JavaScript 字符串 charCodeAt() 方法返回指定索引处 0 到 65535 之间的整数。该整数值被视为单个字符的 Unicode 码。索引从 0 开始,以 str.length-1 结束。
如果索引参数值不在 0 到 str.length-1 的范围内,则返回 'NaN'。
语法
以下是 JavaScript 字符串 charCodeAt() 方法的语法 -
charCodeAt(index)
参数
此方法接受一个名为"index"的可选参数,其解释如下 -
- index - 字符的索引(位置)。
返回值
此方法返回指定位置字符的 Unicode 码索引。
示例 1
当我们省略 index 参数时,此方法将假定其索引参数默认值为 0,并返回给定字符串"Tutorials Point"中第一个字符"T"的 Unicode。
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script>
const str = "Tutorials Point";
document.write("String value = ", str);
document.write("<br>The character code ", str.charCodeAt(), " is equal to ", str.charAt());
</script>
</body>
</html>
输出
上述程序返回字符"T"的 Unicode 编码 84。
String value = Tutorials Point The character code 84 is equal to T
示例 2
如果我们将索引值 6 传递给此方法,它将返回指定索引处字符的 Unicode 码。
以下是 JavaScript 字符串 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
示例 3
当索引参数不在 0 到 str.length-1 之间时,此方法返回 'NaN'。
我们可以通过执行以下程序来验证上述事实陈述:如果索引参数超出 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

