在 JavaScript 中将字母转换为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27877197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert letter to number in JavaScript
提问by Alex Kom
I would like to know how to convert each alphabetic character entered to a number.
我想知道如何将输入的每个字母字符转换为数字。
e.g. a=1, b=2 ,c=3 up to z=26
例如 a=1, b=2 ,c=3 直到 z=26
In C I had managed to do something similar, by taking a character input and displaying it as an integer. But I'm not sure how I would do this in JavaScript.
在 CI 中,通过接受一个字符输入并将其显示为一个整数,设法做一些类似的事情。但我不确定我将如何在 JavaScript 中做到这一点。
采纳答案by Erik van de Ven
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var letter = "h";
var letterPosition = alphabet.indexOf(letter)+1;
EDIT:
编辑:
Possibility to calculate the letters inside a string, aa=2, ab=3 etc.
可以计算字符串中的字母,aa=2,ab=3 等。
function str_split(string, split_length) {
// discuss at: http://phpjs.org/functions/str_split/
// original by: Martijn Wieringa
// improved by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Onno Marsman
// revised by: Theriault
// revised by: Rafa? Kukawski (http://blog.kukawski.pl/)
// input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)
// example 1: str_split('Hello Friend', 3);
// returns 1: ['Hel', 'lo ', 'Fri', 'end']
if (split_length == null) {
split_length = 1;
}
if (string == null || split_length < 1) {
return false;
}
string += '';
var chunks = [],
pos = 0,
len = string.length;
while (pos < len) {
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
function count(string){
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var splitted_string = str_split(string);
var count = 0;
for (i = 0; i < splitted_string.length; i++) {
var letterPosition = alphabet.indexOf(splitted_string[i])+1;
count = count + letterPosition;
}
return count;
}
console.log(count("az")); // returns 27 in the console
回答by leaf
If I get you right, the other answers are over complicated:
如果我猜对了,其他答案就太复杂了:
parseInt('a', 36) - 9; // 1
parseInt('z', 36) - 9; // 26
parseInt('A', 36) - 9; // 1
parseInt('Z', 36) - 9; // 26
function sumChars(s) {
var i, n = s.length, acc = 0;
for (i = 0; i < n; i++) {
acc += parseInt(s[i], 36) - 9;
}
return acc;
}
console.log(sumChars("az"))
However, I rather think of the number "az" as a base 36 integer. Indeed, your notation of an integer is space consuming compared to the positional notation. Compare "baz" in both notations:
但是,我更愿意将数字“az”视为基数为 36 的整数。实际上,与位置表示法相比,您的整数表示法更占用空间。比较两种符号中的“baz”:
sumChars("baz") // 29
parseInt("baz", 36) // 14651
The amount of letters is the same, but the base 36 integer is way bigger. Moreover, convert a base 10 integer to base 36 is trivial in JavaScript:
字母的数量是相同的,但基数为 36 的整数要大得多。此外,将基数为 10 的整数转换为基数 36 在 JavaScript 中是微不足道的:
(14651).toString(36) // "baz"
Be careful though, although it sounds counterintuitive, binary is even more compact. Indeed, one letter occupies at least 8 bits in memory:
不过要小心,虽然这听起来违反直觉,但二进制更紧凑。事实上,一个字母在内存中至少占据 8 位:
(35).toString(2).length // 6 bits long
(35).toString(36).length * 8 // 8 bits long
回答by meskobalazs
In JavaScript characters are not a single byte datatype, so if you want to mimick the workings of C, you need to create a mapping by yourself.
在 JavaScript 中,字符不是单字节数据类型,所以如果你想模仿 C 的工作方式,你需要自己创建一个映射。
For example using a simple object as a map:
例如使用一个简单的对象作为地图:
var characters: {
'a': 1,
'b': 2,
...
}
This way var number = charachters['a'];will set number to 1. The others have provided shorted methods, which are most likely more feasible, this one is mostly aimed for easy understanding.
这种方式var number = charachters['a'];会将 number 设置为1. 其他人提供了短路方法,这很可能是更可行的,这个主要是为了易于理解。
回答by Amit Joki
You could do it like this
你可以这样做
function convertToNumbers(str){
var arr = "abcdefghijklmnopqrstuvwxyz".split("");
return str.replace(/[a-z]/ig, function(m){ return arr.indexOf(m.toLowerCase()) + 1 });
}
What your doing is creating an array of alphabets and then using the callback in String.replacefunction and returning the respective indexes of the letter +1as the indices start from 0
您所做的是创建一个字母数组,然后在String.replace函数中使用回调并返回字母的相应索引+1作为索引开始0
回答by Royi Namir
This will work
这将工作
"abcdefghijklmnopqrstuvwxyz".split("").forEach(function (a,b,c){ console.log(a.toLowerCase().charCodeAt(0)-96)});
"iloveyou".split("").forEach(function (a,b,c){ console.log(a.toLowerCase().charCodeAt(0)-96)});
9
12
15
22
5
25
15
21
回答by kennebec
You can make an object that maps the values-
您可以制作一个映射值的对象-
function letterValue(str){
var anum={
a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11,
l: 12, m: 13, n: 14,o: 15, p: 16, q: 17, r: 18, s: 19, t: 20,
u: 21, v: 22, w: 23, x: 24, y: 25, z: 26
}
if(str.length== 1) return anum[str] || ' ';
return str.split('').map(letterValue);
}
letterValue('zoo')returns: (Array) [26,15,15] ;
letterValue('zoo')返回: (Array) [26,15,15] ;
letterValue('z')returns: (Number) 26
letterValue('z')返回:(数字)26
回答by spencer robertson
You can just get the ascii value and minus 64 for capital letters.
您可以只获得 ascii 值和大写字母的负 64。
var letterPlacement = "A".charCodeAt(0) - 64;
Or minus 96 for lower case.
或负 96 表示小写。
var letterPlacement = "a".charCodeAt(0) - 96;
Or as a nice and tidy one line function that doesn't give a damn about case:
或者作为一个漂亮而整洁的单行函数,它不在乎案例:
function alphabetifier(letter) {
return letter.charCodeAt(0) - (letter === letter.toLowerCase() ? 96 : 64);
}


