Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - Create an array of characters from specified range

I read some code where someone did this in Ruby:

puts ('A'..'Z').to_a.join(',')

output:

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

Is there something in Javascript that will allow this to be done just as easy? if not, is there Node module that allows for something similar?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're using ES6, you can generate a sequence using Array.from() by passing in an array-like object for the length of the range, and a map function as a second argument to convert the array key of each item in the range into a character using String.fromCharCode():

Array.from({ length: 26 }, (_, i) => String.fromCharCode('A'.charCodeAt(0) + i));

You can also use the Array constructor (note: ES6 allows constructors to be invoked either with a function call or with the new operator) to initialize an array of the desired default length, fill it using Array.fill(), then map through it:

Array(26).fill().map((_, i) => String.fromCharCode('A'.charCodeAt(0) + i));

The same can be accomplished with the spread operator:

[...Array(26)].map((_, i) => String.fromCharCode('A'.charCodeAt(0) + i));

The above three examples will return an array with characters from A to Z. For custom ranges, you can adjust the length and starting character.

For browsers that don't support ES6, you can use babel-polyfill or core-js polyfill (core-js/fn/array/from).

If you're targeting ES5, I would recommend the Array.apply solution by @wires which is very similar to this one.

Lastly, Underscore/Lodash and Ramda have a range() function:

_.range('A'.charCodeAt(0), 'Z'.charCodeAt(0) + 1).map(i => String.fromCharCode(i));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...