如何用Javascript将字母转换为数字? [英] How to convert letters to numbers with Javascript?

查看:1024
本文介绍了如何用Javascript将字母转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中将字母转换为相应的数字?

How could I convert a letter to its corresponding number in JavaScript?

例如:

a = 0
b = 1
c = 2
d = 3

我在将数字转换为超过26个字符字母的字母,但它要求相反。

I found this question on converting numbers to letters beyond the 26 character alphabet, but it is asking for the opposite.

有没有办法在没有庞大阵列的情况下做到这一点?

Is there a way to do this without a huge array?

推荐答案

您可以使用 <从字符串中的任何索引获取代码点* code> String.prototype.charCodeAt 。如果你的字符串是单个字符,你需要索引 0 ,而 a 的代码是97(很容易从JavaScript获得'a'.charCodeAt(0)),所以你可以这样做:

You can get a codepoint* from any index in a string using String.prototype.charCodeAt. If your string is a single character, you’ll want index 0, and the code for a is 97 (easily obtained from JavaScript as 'a'.charCodeAt(0)), so you can just do:

s.charCodeAt(0) - 97

如果你想要反过来说, String.fromCharCode 获取Unicode代码点*并返回一个字符串。

And in case you wanted to go the other way around, String.fromCharCode takes Unicode codepoints* and returns a string.

String.fromCharCode(97 + n)

* 不完全

这篇关于如何用Javascript将字母转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆