How to generate an array of alphabet in jQuery?

前端 未结 15 2218
被撕碎了的回忆
被撕碎了的回忆 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:23
    const ALPHA = Array.from({ length: 26 }, (_, i) => String.fromCharCode('a'.charCodeAt(0) + i)); // ['a', 'b', ...'z']
    

    I believe the above code is more idiomatic. Short enough to be an inline code. You don't have to remember the charCode of your start letter and configurable to retrieve subsets of the alphabet by simply controlling the length and start letter e.g

    Array.from({ length: 3 }, (_, i) => String.fromCharCode('x'.charCodeAt(0) + i)) // ['x', 'y', 'z]
    
    0 讨论(0)
  • 2020-12-07 16:26

    I saw an answer I loved above which was the hardcoded list of the english alphabets but it was in lower case only and I needed upper case too so I decided to modify it in case someone else needs it:

    const lowerAlph = ["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"];

    const upperCaseAlp = ["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:30

    A short ES6 version:

    const alphabet = [...'abcdefghijklmnopqrstuvwxyz']
    
    0 讨论(0)
提交回复
热议问题