将数字转换为字母

问题描述 投票:0回答:9

我想将一个数字转换为其对应的字母。例如:

1 = A
2 = B
3 = C

可以在 javascript 中完成此操作,而无需手动创建数组吗? 在 php 中有一个 range() 函数可以自动创建数组。 javascript 中有类似的东西吗?

javascript numbers alphabetical
9个回答
47
投票

是的,带有

Number#toString(36)
和调整。

var value = 10;

document.write((value + 9).toString(36).toUpperCase());


28
投票

您可以使用

String.fromCharCode(code)
函数简单地执行此操作,而无需使用数组,因为字母具有连续的代码。例如:
String.fromCharCode(1+64)
为您提供“A”,
String.fromCharCode(2+64)
为您提供“B”,依此类推。


11
投票

下面的代码片段将字母表中的字符转变为像数字系统一样工作

1 = A
2 = B
...
26 = Z
27 = AA
28 = AB
...
78 = BZ
79 = CA
80 = CB

var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
function printToLetter(number){
    var charIndex = number % alphabet.length
    var quotient = number/alphabet.length
    if(charIndex-1 == -1){
        charIndex = alphabet.length
        quotient--;
    }
    result =  alphabet.charAt(charIndex-1) + result;
    if(quotient>=1){
        printToLetter(parseInt(quotient));
    }else{
        console.log(result)
        result = ""
    }
}

我创建了这个函数来在打印时保存字符,但不得不废弃它,因为我不想处理最终可能形成的不正确的单词


8
投票

只需将 letterIndex 从 0 (A) 增加到 25 (Z)

const letterIndex = 0
const letter = String.fromCharCode(letterIndex + 'A'.charCodeAt(0))

console.log(letter)

4
投票

更新(5/2/22):在我在第二个项目中需要此代码后,我决定增强以下答案并将其转换为一个名为

alphanumeric-encoder
的现成可用的 NPM 库。如果您不想构建自己的解决方案来解决此问题,请查看该库!


我构建了以下解决方案作为对 @esantos 答案的增强。

第一个函数定义一个有效的查找编码字典。在这里,我使用了英文字母表中的全部 26 个字母,但以下字母也同样有效:

"ABCDEFG"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
"GFEDCBA"
。使用这些字典之一会将您的 10 基数转换为具有适当编码数字的
dictionary.length
基数。唯一的限制是字典中的每个字符必须是唯一的。

function getDictionary() {
    return validateDictionary("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

    function validateDictionary(dictionary) {
        for (let i = 0; i < dictionary.length; i++) {
            if(dictionary.indexOf(dictionary[i]) !== dictionary.lastIndexOf(dictionary[i])) {
                console.log('Error: The dictionary in use has at least one repeating symbol:', dictionary[i])
                return undefined
            }
        }
        return dictionary
    }
}

我们现在可以使用这个字典来编码我们的 10 基数。

function numberToEncodedLetter(number) {
    //Takes any number and converts it into a base (dictionary length) letter combo. 0 corresponds to an empty string.
    //It converts any numerical entry into a positive integer.
    if (isNaN(number)) {return undefined}
    number = Math.abs(Math.floor(number))

    const dictionary = getDictionary()
    let index = number % dictionary.length
    let quotient = number / dictionary.length
    let result
    
    if (number <= dictionary.length) {return numToLetter(number)}  //Number is within single digit bounds of our encoding letter alphabet

    if (quotient >= 1) {
        //This number was bigger than our dictionary, recursively perform this function until we're done
        if (index === 0) {quotient--}   //Accounts for the edge case of the last letter in the dictionary string
        result = numberToEncodedLetter(quotient)
    }

    if (index === 0) {index = dictionary.length}   //Accounts for the edge case of the final letter; avoids getting an empty string
    
    return result + numToLetter(index)

    function numToLetter(number) {
        //Takes a letter between 0 and max letter length and returns the corresponding letter
        if (number > dictionary.length || number < 0) {return undefined}
        if (number === 0) {
            return ''
        } else {
            return dictionary.slice(number - 1, number)
        }
    }
}

编码的字母集很棒,但如果我不能将其转换回以 10 为基数的数字,那么它对计算机来说就没用了。

function encodedLetterToNumber(encoded) {
    //Takes any number encoded with the provided encode dictionary 

    const dictionary = getDictionary()
    let result = 0
    let index = 0

    for (let i = 1; i <= encoded.length; i++) {
        index = dictionary.search(encoded.slice(i - 1, i)) + 1
        if (index === 0) {return undefined} //Attempted to find a letter that wasn't encoded in the dictionary
        result = result + index * Math.pow(dictionary.length, (encoded.length - i))
    }

    return result
}

现在测试一下:

console.log(numberToEncodedLetter(4))     //D
console.log(numberToEncodedLetter(52))    //AZ
console.log(encodedLetterToNumber("BZ"))  //78
console.log(encodedLetterToNumber("AAC")) //705

更新

您还可以使用此函数获取您拥有的短名称格式并将其返回为基于索引的格式。

function shortNameToIndex(shortName) {
    //Takes the short name (e.g. F6, AA47) and converts to base indecies ({6, 6}, {27, 47})

    if (shortName.length < 2) {return undefined}    //Must be at least one letter and one number
    if (!isNaN(shortName.slice(0, 1))) {return undefined}  //If first character isn't a letter, it's incorrectly formatted

    let letterPart = ''
    let numberPart= ''
    let splitComplete = false
    let index = 1

    do {
        const character = shortName.slice(index - 1, index)
        if (!isNaN(character)) {splitComplete = true}
        if (splitComplete && isNaN(character)) {
            //More letters existed after the numbers. Invalid formatting.
            return undefined    
        } else if (splitComplete && !isNaN(character)) {
            //Number part
            numberPart = numberPart.concat(character)
        } else {
            //Letter part
            letterPart = letterPart.concat(character)
        }
        index++
    } while (index <= shortName.length)

    numberPart = parseInt(numberPart)
    letterPart = encodedLetterToNumber(letterPart)

    return {xIndex: numberPart, yIndex: letterPart}
}

1
投票

有一个单行函数

numAbbr
用于将数字转换为字符串,例如

1 => A
2 => B
...
26 => Z
27 => AA
28 => AB
...
702 => ZZ
703 => AAA
const numAbbr = num => num <= 0 ? '' : numAbbr(Math.floor((num - 1) / 26)) + String.fromCharCode((num - 1) % 26 + 65);

相反的函数

abbrNum
AAA
等字符串转换为数字


const abbrNum = abbr => abbr.toUpperCase().split("").reduce((acc, val) => acc * 26 + val.charCodeAt(0) - 64, 0);

0
投票

这个问题的代码答案确实过于复杂,可以用一个简单的循环来实现

function colToLetter(number){
  let result = '';
  // number = number - 1; // If starting from 1
  do {
    const letter = String.fromCharCode(65 + (number % 26));
    result = letter + result;
    number = Math.floor(number / 26) - 1;
  } while (number >= 0)
  return result;
}

console.log(colToLetter(0));
console.log(colToLetter(25));
console.log(colToLetter(26));
console.log(colToLetter(702));
console.log(colToLetter(728));

这提供了类似Excel的编号功能


0
投票

String.fromCharCode(code)
不需要循环和数组就可以很好地工作。

var index = 1;
console.log(String.fromCharCode(index + 64));

-1
投票

这可以帮助你

static readonly string[] Columns_Lettre = new[] { "A", "B", "C"};

public static string IndexToColumn(int index)
    {
        if (index <= 0)
            throw new IndexOutOfRangeException("index must be a positive number");

        if (index < 4)
            return Columns_Lettre[index - 1];
        else
            return index.ToString();
    }
© www.soinside.com 2019 - 2024. All rights reserved.