创建指定范围内的字符数组 [英] Create an array of characters from specified range
问题描述
我读了一些用Ruby编写的代码:
I read some code where someone did this in Ruby:
puts ('A'..'Z').to_a.join(',')
输出:
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
中是否有某些东西可以使之轻松实现?如果没有,是否有Node模块可以允许类似的东西?
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?
推荐答案
JavaScript本身没有该功能.在下面,您可以找到一些有关如何解决该问题的示例:
Javascript doesn't have that functionality natively. Below you find some examples of how it could be solved:
正常功能,基本平面中的任何字符(不检查代理对)
Normal function, any characters from the base plane (no checking for surrogate pairs)
function range(start,stop) {
var result=[];
for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
result.push(String.fromCharCode(idx));
}
return result;
};
range('A','Z').join();
与上面相同,但作为添加到数组原型的函数,因此可用于所有数组:
The same as above, but as a function added to the array prototype, and therefore available to all arrays:
Array.prototype.add_range = function(start,stop) {
for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
this.push(String.fromCharCode(idx));
}
return this;
};
[].add_range('A','Z').join();
预选字符的范围.比上面的函数快,并且让您使用 alphanum_range('A','z')
表示A-Z和a-z:
A range from preselected characters. Is faster than the functions above, and let you use alphanum_range('A','z')
to mean A-Z and a-z:
var alphanum_range = (function() {
var data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split('');
return function (start,stop) {
start = data.indexOf(start);
stop = data.indexOf(stop);
return (!~start || !~stop) ? null : data.slice(start,stop+1);
};
})();
alphanum_range('A','Z').join();
或ascii范围内的任何字符.通过使用缓存的数组,它比每次构建数组的函数都要快.
Or any character from the ascii range. By using a cached array, it is faster than the functions that build the array every time.
var ascii_range = (function() {
var data = [];
while (data.length < 128) data.push(String.fromCharCode(data.length));
return function (start,stop) {
start = start.charCodeAt(0);
stop = stop.charCodeAt(0);
return (start < 0 || start > 127 || stop < 0 || stop > 127) ? null : data.slice(start,stop+1);
};
})();
ascii_range('A','Z').join();
这篇关于创建指定范围内的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!