如何在JavaScript中找到给定字符串的数值?

时间:2021-11-11 19:24:20

I did some digging on SO and discovered that a question like this has got a lot of ire from the community. So I'll just clarify for those who haven't got it yet.

我在SO上做了一些挖掘,发现像这样的问题引起了很多社区的愤怒。所以我会澄清那些还没有得到它的人。

Say I have a string like "Aravind". The numerical value of that string in cryptography would be:
1 18 1 22 9 14 4." This happens because, in "Aravind", the first letter "A" is the first letter in the alphabet, so the numerical value of "A" would be 1. Same with "R", the 18th letter, so numerical value of "R" is 18. This keeps on going.

说我有一个像“Aravind”的字符串。密码学中该字符串的数值将是:1 18 1 22 9 14 4.“这是因为,在”Aravind“中,第一个字母”A“是字母表中的第一个字母,因此”A“的数值“将是1.与第18个字母”R“相同,因此”R“的数值为18.这一直在继续。

So right now I'm creating a program which includes converting a given string to it's numerical value.

所以现在我正在创建一个程序,包括将给定的字符串转换为它的数值。

var latin_array = ["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 integ_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12 , 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26];

function parseToNumber (str) {
    var spl = str.split("");
    spl.forEach(function (x) {
        latin_array.forEach(function (y) {
            if (x == y) {
                // whatever i want goes here
            }
        })
    })
}

This is how far I've gotten, and I know anyway I made a hundred mistakes. Please forgive me, I'm just 12! So, again I want the numerical a=1, b=2, c=3, d=4 kind of value.

这是我已经走了多远,而且无论如何我知道我犯了一百个错误。请原谅我,我才12岁!所以,我再次想要数值a = 1,b = 2,c = 3,d = 4种值。

Thanks in advance!

提前致谢!

1 个解决方案

#1


2  

Will something like this work?

这样的东西会起作用吗?

function alphabetPosition(text) {
  var result = "";
  for (var i = 0; i < text.length; i++) {
    var code = text.toUpperCase().charCodeAt(i)
    if (code > 64 && code < 91) result += (code - 64) + " ";
  }

  return result.slice(0, result.length - 1);
}
console.log(alphabetPosition("Aravind"));

I get 1 18 1 22 9 14 4 for Aravind. I bet the original Kata is same.

我得到1 18 1 22 9 14 4为Aravind。我打赌原来的Kata是一样的。

#1


2  

Will something like this work?

这样的东西会起作用吗?

function alphabetPosition(text) {
  var result = "";
  for (var i = 0; i < text.length; i++) {
    var code = text.toUpperCase().charCodeAt(i)
    if (code > 64 && code < 91) result += (code - 64) + " ";
  }

  return result.slice(0, result.length - 1);
}
console.log(alphabetPosition("Aravind"));

I get 1 18 1 22 9 14 4 for Aravind. I bet the original Kata is same.

我得到1 18 1 22 9 14 4为Aravind。我打赌原来的Kata是一样的。