ASCII 代表美国信息交换标准代码。
ASCII 是赋予不同字符和符号以供计算机存储和操作的数值。例如,字母 'A' 的 ASCII 值是 65。
资源: JavaScript 中所有 127 个字符的 ASCII 图表。
示例 1: 使用 charCodeAt() 获取字符的 ASCII 值
// program to find the ASCII value of a character // take input from the user const string = prompt('Enter a character: '); // convert into ASCII value const result = string.charCodeAt(0); console.log(`The ASCII value is: ${result}`);
输出
Enter a character: a The ASCII value is: 97
在上面的程序中,
charCodeAt()
方法用于查找字符的ASCII值。
charCodeAt()
方法接受一个索引值并返回一个表示其 UTF-16(16 位 Unicode 转换格式)代码的整数。
如果不传递索引值,则默认索引值为0。如果索引值超出范围,则给出
NaN
。
示例 2: 使用 codePointAt() 获取字符的 ASCII 值
// program to find the ASCII value of a character // take input from the user const string = prompt('Enter a character: '); // convert into ASCII value const result = string.codePointAt(0); console.log(`The ASCII value is: ${result}`);
输出
Enter a character: abc The ASCII value is: 97
在上面的程序中,
codePointAt()
方法是用来求一个字符的ASCII值的。
codePointAt()
方法返回一个 Unicode 代码点值。
在上面的程序中,用户输入三字符的字符串
abc。但是,索引 0 被传递给
codePointAt()
方法。这给出了第一个字符的 ASCII 值(此处为
a)。
如果不传递索引值,则默认索引值为0。如果索引值超出范围,则给出
undefined
。