ASCII 是 美式信息交换标准代码 (American Standard Code for Information Interchange) 的缩写。
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()
方法。这会给出第一个字符(此处为 a)的 ASCII 值。
如果不传递索引值,默认索引值为 0。如果索引值超出范围,则返回 undefined
。