将整数转换为其在 JavaScript 中等效的字符

将整数转换为 JavaScript 中的等价字符

Convert Integer to its Character Equivalent in JavaScript

要将整数转换为其等效字符:

  1. 使用charCodeAt()方法获取字母的字符代码a
  2. fromCharCode()使用整数和字符代码的总和调用该方法。
索引.js
function intToChar(int) { // 👇️ for Uppercase letters, replace `a` with `A` const code = 'a'.charCodeAt(0); console.log(code); // 👉️ 97 return String.fromCharCode(code + int); } console.log(intToChar(0)); // 👉️ "a" console.log(intToChar(4)); // 👉️ "e"

我们使用
String.charCodeAt
来获取字母的字符代码
a

的字符代码a97

索引.js
console.log('a'.charCodeAt(0)); // 👉️ 97

charCodeAt方法采用的唯一参数是要获取其字符代码的字符串中字符的索引。

将整数转换为其等效的大写字符

如果您需要将整数转换为大写字符,请改为获取字母的字符代码A(65)。

索引.js
function intToChar(int) { const code = 'A'.charCodeAt(0); console.log(code); // 👉️ 65 return String.fromCharCode(code + int); } console.log(intToChar(0)); // 👉️ "A" console.log(intToChar(4)); // 👉️ "E"

请注意,我们String.charCodeAt对大写字母调用了该方法A以将整数转换为其等效的大写字符。

最后一步是使用
String.fromCharCode
方法获取整数的等效字符。

该方法将一个或多个数字作为参数,并返回一个包含数字代码单元的字符串。

通过将字母的字符代码a与整数相加,我们从0, where 0is a, 1isb等开始计数。

您可以使用 方法将字符转换回整数charCodeAt

# Convert the character back to its integer equivalent

To convert a character back to its integer equivalent:

  1. Use the charCodeAt method to get the UTF-16 code unit of the letter a.
  2. Use the charCodeAt method to get the code unit of the character.
  3. Subtract the code unit of the letter a from the code unit of the character.
index.js
function charToInt(char) { const code = 'a'.charCodeAt(0); return char.charCodeAt(0) - code; } console.log(charToInt('a')); // 👉️ 0 console.log(charToInt('e')); // 👉️ 4

The first step is to get the UTF-16 code unit of the letter a.

Then, we subtract the character code of the letter a from the character code
of the supplied character.

The function returns the integer equivalent of the character.

# Additional Resources

You can learn more about the related topics by checking out the following
tutorials: