我最近一直试图编写一个问题,其中一些JS代码将字母转换为数字,例如。 1 =
我当前的代码如下(使用HTML脚本标记):
option.php
然而,每当我尝试将对应于x(24)的数字转换为字母时,它就会给我“bd”,因为它分别处理2和4。有没有一种简单的方法可以阻止它,所以当我键入24时,它会产生“x”?
答案 0 :(得分:0)
当您循环输入时,您正在调用input.charAt(i)
,但这样一次只能拉出一个字符。如果您希望它拉两位数,您需要编写代码来执行此操作。否则,该数字一次读取并处理一位数。
拉出单个字符时,请检查它是否在0到9之间(包括0和9)。如果是,则循环接下来的几个字符并在将其传递到switch
之前构建所需的字符串,这样您就可以获得所需的多位数输入。
答案 1 :(得分:0)
您应该执行以下操作:
function covert(input)
{
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 nums=["1","2","3","4","5","6","7","8","9","1-0","1-1","1-2","1-3","1-4","1-5","1-6","1-7,"1-8","1-9","2-0","2-1",2-2","2-3","2-4",2-5",2-6"]
var letters = input.lowerCase().split("");
for(var i=0;i<letters.length;i++)
if(letters[i].lowerCase != letters[i].toUpperCase()) //Checking if it's a letter
phonenumber+=toString(alphabet.indexOf(letter[i])+1;);
var dashesAndNum=input.replace(/[A-Za-z],' ').split(" ");
for(var i=0;i<dashesAndNum.length;i++)
if(dashesAndNum[i] == "0" || dashesAndNum[i] == "-")
phonenumber+=dashesAndNum[i];
else
phonenumber+=alphabet[num.indexOf(dashesAndNum[i])];
document.myform.number.value = phonenumber;
return true;
}
答案 2 :(得分:0)
在生成的数字之间理解-
。这意味着,您无法对数字包围的-
进行编码。
function convert(input) {
var inputlength = input.length,
CODE = '0abcdefghijklmnopqrstuvwxyz',
phonenumber = "",
character,
i;
input = input.toLowerCase();
for (i = 0; i < inputlength; i++) {
character = input[i];
if (isFinite(input[i]) && '-' === input[i + 1] && isFinite(input[i+2])) {
i += 2;
character += input[i];
}
phonenumber += ~CODE.indexOf(character) ? ('' + CODE.indexOf(character)).split('').join('-') : (character === '-' ? '-' : CODE[character]);
}
document.myform.number.value = phonenumber;
return true;
}
克服-
问题的正确解决方案是将不同的字符实现为2位数字的符号,可能是|
,因此代码如下所示:
function convert(input) {
var inputlength = input.length,
CODE= '0abcdefghijklmnopqrstuvwxyz',
SEPARATOR = '|',
phonenumber = "",
character,
i;
input = input.toLowerCase();
for (i = 0; i < inputlength; i++) {
character = input[i];
if (isFinite(input[i]) && SEPARATOR === input[i + 1] && isFinite(input[i + 2])) {
i += 2;
character += input[i];
}
phonenumber += ~CODE.indexOf(character) ? ('' + CODE.indexOf(character)).split('').join(SEPARATOR) : (character === '-' ? '-' : CODE[character]);
}
document.myform.number.value = phonenumber;
return true;
}
答案 3 :(得分:-1)
试试这个:
String.fromCharCode(96+24)
您可以将24替换为其他数字。