How to generate an array of alphabet in jQuery?

前端 未结 15 2178
被撕碎了的回忆
被撕碎了的回忆 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:07

    In case anyone came here looking for something they can hard-code, here you go:

    ["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"]

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

    Try

    [...Array(26)].map((x,i)=>String.fromCharCode(i + 97))
    

    let alphabet = [...Array(26)].map((x,i)=>String.fromCharCode(i + 97));
    
    console.log(alphabet);

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

    By using ES6 spread operator you could do something like this:

    let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));
    
    0 讨论(0)
  • 2020-12-07 16:10

    in case if you need a hard-coded array of the alphabet, but with a less typing. an alternative solution of what mentioned above.

    var arr = "abcdefghijklmnopqrstuvwxyz".split("");
    

    will output an array like this

    /* ["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"] */
    
    0 讨论(0)
  • 2020-12-07 16:12

    Just for fun, then you can define a getter on the Array prototype:

    Object.defineProperty(Array.prototype, 'to_a', {
      get: function () {
        const start = this[0].charCodeAt(0);
        const end = this[1].charCodeAt(0);
        return Array.from(Array(end - start + 1).keys()).map(n => String.fromCharCode(start + n));
      }
    });
    

    Which makes it possible to do something like:

    ['a', 'z'].to_a; // [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", ..., "z" ]
    
    0 讨论(0)
  • 2020-12-07 16:14

    Generate Character List with one-liner

    const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));
    
    console.log("from A to G", charList('A', 'G'));
    console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
    console.log("reverse order from Z to P", charList('Z', 'P', -1));
    console.log("from 0 to 5", charList('0', '5', 1));
    console.log("from 9 to 5", charList('9', '5', -1));
    console.log("from 0 to 8 with step 2", charList('0', '8', 2));
    console.log("from α to ω", charList('α', 'ω'));
    console.log("Hindi characters from क to ह", charList('क', 'ह'));
    console.log("Russian characters from А to Я", charList('А', 'Я'));

    For TypeScript
    const charList = (p: string, q: string, d = 1) => {
      const a = p.charCodeAt(0),
        z = q.charCodeAt(0);
      return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
        String.fromCharCode(a + i * d)
      );
    };
    
    0 讨论(0)
提交回复
热议问题