Increment a string with letters?

前端 未结 12 1279
礼貌的吻别
礼貌的吻别 2021-02-08 12:35

I need to increment a string from.. let\'s say aaa to zzz and write every incrementation in the console (is incrementation even a word?). It would go s

12条回答
  •  死守一世寂寞
    2021-02-08 13:13

    Let's try this approach. It's a straight loop which produces the complete sequence from aaa,aab,aac,.....,xzz,yzz,zzz

    function printSeq(seq){
        console.log(seq.map(String.fromCharCode).join(''));
    }
    
    
    var sequences = [];
    
    (function runSequence(){
        var seq = 'aaa'.split('').map(function(s){return s.charCodeAt(0)});
        var stopCode = 'z'.charCodeAt(0);
        do{
            printSeq(seq);
            sequences.push(seq.map(String.fromCharCode).join(''));
            if (seq[2]!=stopCode) seq[2]++;
            else if (seq[1]!=stopCode) seq[1]++;
            else if (seq[0]!=stopCode) seq[0]++;
        }while (seq[0]

    The results are displayed in the console and also you'll get a complete sequence stored in sequence array. Hope this is readable and helpful.

提交回复
热议问题