如何从Javascript中的字符串快速生成数组

时间:2019-05-24 00:33:01

标签: javascript arrays ruby string

在ruby中,我可以使用以下代码生成从a到z的字符串数组:

alphabet = ('a'..'z').to_a
=> ["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"]

在Javascript中是否有类似的函数调用?

2 个答案:

答案 0 :(得分:3)

不幸的是,ECMAScript在其标准库中没有Range。但是,您可以做的是使用Array.from工厂函数通过映射函数构造一个Array

类似这样的东西:

const alphabet = Array.from({ length: 26 }, (_, i) => i + 97).map(String.fromCharCode);

或者,没有魔术数字:

const charCodeOfA = "a".charCodeAt(0),                //=>  97
    charCodeOfZ = "z".charCodeAt(0),                  //=> 122
    lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1, //=>  26

    alphabet = Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
        map(String.fromCharCode);

在将来的ECMAScript版本中,最好使用do expressions来避免使用这些临时帮助程序变量污染名称空间:

const alphabet = do {
    const charCodeOfA = "a".charCodeAt(0),                //=>  97
        charCodeOfZ = "z".charCodeAt(0),                  //=> 122
        lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1; //=>  26

    Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
        map(String.fromCharCode)
}

答案 1 :(得分:2)

最简单的方法是

var alphabet =[];
for(var i = "a".charCodeAt(0); i <= "z".charCodeAt(0); i++) {
        alphabet.push(String.fromCharCode(i))

}