fab*_*bbb 40 javascript jquery
在Ruby中,我可以做到('a'..'z').to_a并且得到['a', 'b', 'c', 'd', ... 'z'].
jQuery或Javascript提供类似的构造吗?
Mic*_*rst 102
我个人认为最好的是:
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
Run Code Online (Sandbox Code Playgroud)
简洁,有效,清晰,简单!
编辑: 我已经决定,因为我的答案得到了相当多的关注,添加了选择特定字母范围的功能.
function to_a(c1 = 'a', c2 = 'z') {
a = 'abcdefghijklmnopqrstuvwxyz'.split('');
return (a.slice(a.indexOf(c1), a.indexOf(c2) + 1));
}
Run Code Online (Sandbox Code Playgroud)
Pau*_* S. 33
如果您需要它,您可以轻松地为您执行此功能
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"]
Run Code Online (Sandbox Code Playgroud)
men*_*ode 27
new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );
Run Code Online (Sandbox Code Playgroud)
使用97而不是65来获取小写字母.
Hen*_*ash 22
简短的ES6版本:
const alphabet = [...'abcdefghijklmnopqrstuvwxyz']
Run Code Online (Sandbox Code Playgroud)
Bry*_*son 19
如果有人来这里寻找他们可以硬编码的东西,你可以去:
["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"]
如果您需要array对字母表进行硬编码,但需要减少打字次数。上述解决方案的替代解决方案。
var arr = "abcdefghijklmnopqrstuvwxyz".split("");
Run Code Online (Sandbox Code Playgroud)
将输出一个像这样的数组
/* ["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"] */
Run Code Online (Sandbox Code Playgroud)
通过使用ES6传播运算符,您可以执行以下操作:
let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));
Run Code Online (Sandbox Code Playgroud)
小智 8
很多这些答案要么使用字符数组,要么String.fromCharCode我提出了一种稍微不同的方法,它利用了 base36 中的字母:
[...Array(26)].map((e,i)=>(i+10).toString(36))
Run Code Online (Sandbox Code Playgroud)
这个的优点是纯粹的代码高尔夫,它使用的字符比其他的少。
[...8337503854730415241050377135811259267835n.toString(36)]
Run Code Online (Sandbox Code Playgroud)
// chrome & firefox
let a1 = [...8337503854730415241050377135811259267835n.toString(36)];
console.log(a1);
// version working on all browsers (without using BigInt)
let a2 = [...[37713647386641440,2196679683172530,53605115].map(x=>x.toString(36)).join``];
console.log(a2);Run Code Online (Sandbox Code Playgroud)
我在上面看到了一个我喜欢的答案,它是英文字母的硬编码列表,但它仅是小写字母,我也需要大写字母,因此我决定对它进行修改,以防其他人需要它:
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"];