String charCodeAt()
JavaScript String charCodeAt()方法
JavaScript字符串
charCodeAt()方法用于找出特定索引处字符的Unicode值
索引号从0开始到n-1,其中n是字符串的长度。如果给定的索引号为负数或大于或等于字符串的长度,则返回
NaN 。
语法
charCodeAt()方法由以下语法表示:
参数
索引-表示字符的位置。
返回
一个Unicode值
JavaScript字符串charCodeAt()方法示例
看到一些简单的charCodeAt()方法示例。
示例1
在这里,我们将通过传递字符的特定索引来打印字符的Unicode值。
<script>
var x="lidihuo";
document.writeln(x.charCodeAt(3));
</script>
输出:
示例2
在此示例中,我们将不使用该方法传递任何索引号。在这种情况下,它将返回第一个字符的Unicode值。
<script>
var x="lidihuo";
document.writeln(x.charCodeAt());//It will return Unicode value of 'J'
</script>
输出:
示例3
在这里,我们将在字符串中打印最后一个字符的Unicode值。
<script>
var x="lidihuo";
document.writeln(x.charCodeAt(x.length-1));
</script>
输出:
示例4
在这里,我们将提供大于字符串长度的索引号。在这种情况下,该方法将返回NaN。
<script>
var x="lidihuo";
document.writeln(x.charCodeAt(12));
</script>
输出: