Count with A, B, C, D instead of 0, 1, 2, 3, … with JavaScript

拥有回忆 提交于 2019-12-10 03:01:01

问题


This is probably an unusual request, but for my script I need a function that increments by letter instead of number. For example:

This is a numeric example:

var i = 0;
while(condition){
 window.write('We are at '+i);
 ++i;
}

Essentially, I want to count with letters, like Microsoft Excel does, instead of numbers. So instead of printing "We are at 0", "We are at 1", "We are at 2", etc., I need to print "We are at A", "We are at B", "We are at C", etc.

To mimic Excel (the only example I can think of), after reaching index 25 (Z), we could move on to 'AA', 'AB', 'AC', etc.

So it would work great like so:

var i = 0;
while(condition){
 window.write('We are at '+toLetter(i));
 ++i;
}

Even better if somebody can write a function that then converts a letter back into a digit, i.e. toNumber('A') = 0 or toNumber('DC') = 107 (I think).

Thanks!


回答1:


Here's a simple recursive function to convert the numbers to letters.

It's one-based, so 1 is A, 26 is Z, 27 is AA.

function toLetters(num) {
    "use strict";
    var mod = num % 26,
        pow = num / 26 | 0,
        out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
    return pow ? toLetters(pow) + out : out;
}

Here's a matching function to convert the strings back to numbers:

function fromLetters(str) {
    "use strict";
    var out = 0, len = str.length, pos = len;
    while (--pos > -1) {
        out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - 1 - pos);
    }
    return out;
}

A test: http://jsfiddle.net/St6c9/




回答2:


Something like this you mean?

function num2chars(num, upper){
 num2chars.letters = num2chars.letters || 'abcdefghijklmnopqrstuvwxyz'.split('');
 var ret = repeat(num2chars.letters[num%26],Math.floor(num/26));

 function repeat(chr,n){
  if (n<1) {return chr;}
  return new Array(n+1).join(chr);
 }

 return upper ? ret.toUpperCase() : ret;
}
//usage
while(i<104){
 console.log(num2chars((i+=1),true));
}
//=> A..Z, AA..ZZ, AAA..ZZZ



回答3:


Create an array of letters A, B, C, D, etc. then call A by using array[0] since 0 is the index of A you can use array[i] as the index, just validate so i can't be over 25.

Use either of these ways to create the array:

var alphabet = new Array("A","B","C");

var alphabet = new Array(25);
alphabet[0] = "A";
alphabet[1] = "B";
alphabet[2] = "C";

instead of toLetter(i); use alphabet[i];




回答4:


Try the following. Tried and tested in few minutes

 var prefix = Array('','A','B'); //this will extends to 3x26 letters. Determines the Max generated
//first element of prefix is `''` so you can have A B C D
var prefix = Array('','A','B');
var alphabets = Array('A','B','C','D'); //extend this to Z
var letters = Array();

function fillArray()
{
   var prefix_len = prefix.length;
   var array_len = prefix_len * alphabets.length;
   var alpha_len = alphabets.length;

   for(var i=0; i<prefix_len; i++)
   {
      for(var a=0; a<alpha_len; a++)
         letters.push(''+prefix[i]+alphabets[a]);
   }



}

function getLetter(index)
{
  return letters[index];
}


function generateTestValues() 
{
  fillArray();
  //make sure 10 is less than letters.length
  for(var i=0; i<10; i++)
     document.write(getLetter(i)+' ');  //A B C D AA AB AC AD BA BB BC....
}

HTML

<span id="clickable" onclick="generateTestValues()">Click Me</span>



回答5:


Thats how you can generate random letters:

function getRandomArbitrary(min, max) {
  max = Math.ceil(max);
  min = Math.floor(min); 
  return Math.round(Math.random() * (max - min) + min);
}

function assignLetter(){
  var group = ['A', 'B', 'C', 'D'];
  var text = 'We are at ';
  var str = '';
  str = text + group[getRandomArbitrary(0, group.length-1)];
  return str;
}
assignLetter();


来源:https://stackoverflow.com/questions/11089399/count-with-a-b-c-d-instead-of-0-1-2-3-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!