How to generate an array of alphabet in jQuery?

前端 未结 15 2179
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 15:57

In Ruby I can do (\'a\'..\'z\').to_a and to get [\'a\', \'b\', \'c\', \'d\', ... \'z\'].

Do jQuery or Javascript provide a similar construc

相关标签:
15条回答
  • 2020-12-07 16:15

    You can easily make a function to do this for you if you'll need it a lot

    function genCharArray(charA, charZ) {
        var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
        for (; i <= j; ++i) {
            a.push(String.fromCharCode(i));
        }
        return a;
    }
    genCharArray('a', 'z'); // ["a", ..., "z"]
    
    0 讨论(0)
  • 2020-12-07 16:17

    Personally I think the best is:

    alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
    

    Concise, effective, legible, and simple!

    EDIT: I have decided, that since my answer is receiving a fair amount of attention to add the functionality to choose specific ranges of letters.

    function to_a(c1 = 'a', c2 = 'z') {
        a = 'abcdefghijklmnopqrstuvwxyz'.split('');
        return (a.slice(a.indexOf(c1), a.indexOf(c2) + 1)); 
    }
    
    0 讨论(0)
  • 2020-12-07 16:22
    new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );
    

    Use 97 instead of 65 to get the lowercase letters.

    0 讨论(0)
  • 2020-12-07 16:22

    A lot of these answers either use an array of characters or String.fromCharCode, I propose a slightly different method that takes advantage of letters in base36:

    [...Array(26)].map((e,i)=>(i+10).toString(36))
    

    The advantage of this one is purely code golf, it uses fewer characters than the others.

    0 讨论(0)
  • 2020-12-07 16:22

    No Javascript or Jquery doesnot provide anything like that. You have to create your own array.

    You may try like this:

    var alpha = ["a","b","c",....];
    

    or better try like this:

    var index = 97;
    $("#parent .number").each(function(i) {
        $(this).html(String.fromCharCode(index++));
    });
    

    DEMO

    0 讨论(0)
  • 2020-12-07 16:23

    Using JavaScript's Array.from syntax allows you to create an array and perform a mapping function on each of the array elements. Create a new array of length 26 and on each element set the value equal to the string obtained from the char code of the index of the current element plus the ascii magic number.

    const alphabet = Array.from(Array(26), (e, i) => String.fromCharCode(i + 97));
    

    Again, 97 may be interchanged with 65 for an uppercase alphabet.

    The array may also be initialized with values using the object's keys method rather than utilising the index of the map

    const alphabet = Array.from(Array(26).keys(), i => String.fromCharCode(i + 97));
    
    0 讨论(0)
提交回复
热议问题