Javascript 从指定范围创建字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12376870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:50:52  来源:igfitidea点击:

Create an array of characters from specified range

javascriptrubynode.js

提问by EhevuTov

I read some code where someone did this in Ruby:

我读了一些代码,有人用 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 Javascriptthat will allow this to be done just as easy? if not, is there Node module that allows for something similar?

有什么东西Javascript可以让这件事变得同样容易吗?如果没有,是否有 Node 模块允许类似的东西?

采纳答案by some

Javascript doesn't have that functionality natively. Below you find some examples of how it could be solved:

Javascript 本身没有该功能。您可以在下面找到一些如何解决的示例:

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();

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:

预选字符的范围。比上面的函数还快,让你alphanum_range('A','z')用来表示AZ和az:

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();

Or any character from the ascii range. By using a cached array, it is faster than the functions that build the array every time.

或 ascii 范围内的任何字符。通过使用缓存数组,它比每次构建数组的函数都要快。

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();

回答by Brian Stanback

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():

如果您使用的是 ES6,您可以使用Array.from()生成一个序列,方法是传入一个类似数组的对象作为范围的长度,以及一个 map 函数作为第二个参数来转换每个项目的数组键使用 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 newoperator) to initialize an array of the desired default length, fill it using Array.fill(), then map through it:

您还可以使用 Array 构造函数(注意:ES6 允许使用函数调用或new运算符调用构造函数)来初始化所需默认长度的数组,使用Array.fill()填充它,然后通过它进行映射:

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.

以上三个示例将返回一个包含从 A 到 Z 字符的数组。对于自定义范围,您可以调整长度和起始字符。

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

对于不支持 ES6 的浏览器,可以使用 babel-polyfill 或 core-js polyfill (core-js/fn/array/from)。

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

如果你的目标是 ES5,我会推荐@wires 的 Array.apply 解决方案,它与这个非常相似。

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

最后,Underscore/Lodash 和 Ramda 有一个 range() 函数:

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

回答by gray state is coming

var chars = [].concat.apply([], Array(26))
              .map(function(_, i) { return String.fromCharCode(i+65); })
              .join();

The .mapfunction could be a function generator that could be used for different character sets.

.map函数可以是可用于不同字符集的函数生成器。

function charRange(start) {
    var base = start.charCodeAt(0);
    return function(_, i) { return String.fromCharCode(i + base); };
}

And you may also want to create a "full" Array helper.

您可能还想创建一个“完整的”数组助手。

function fullArray(len) { return [].concat.apply([], Array(len)); }

Then use them like this.

然后像这样使用它们。

var chars = fullArray(26).map(charRange("A"))
                         .join();

回答by Marc J. Schmidt

Take a look at the answer from kannebec for a similar question.

看看 kannebec 对类似问题的回答。

Does JavaScript have a method like "range()" to generate an array based on supplied bounds?

JavaScript 有没有像“range()”这样的方法来根据提供的边界生成数组?

If you don't want to add an own function, but in one line:

如果您不想添加自己的函数,而是在一行中:

var abc = 
(function(){var output = []; for(var i='A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++)
    output.push(String.fromCharCode(i)); return output;})().join(',');

回答by wires

TL;DR

TL; 博士

// ['a', .. , 'z']
Array.apply(null, {length: 26})
    .map(function (x,i) { return String.fromCharCode(97 + i) });

Or even

甚至

function range(first, last) {
    var a = first.charCodeAt(0)
    var b = last.charCodeAt(0) + 1
    return Array.apply(null, {length: Math.abs(b - a)})
      .map(function (x,i) { return String.fromCharCode(Math.min(a, b) + i) });
}
range('K','M') // => ['K','L','M']
range('$','z') // => "$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz"


I think this can be expressed clearest in a functional way: map [0 .. 25]to ['a' .. 'z'].

我认为这可以用函数式的方式表达得最清楚:映射[0 .. 25]['a' .. 'z'].

We can use fromCharCode(n)to convert a number into a string. To find the numerical value corresponding to a character we need it's inverse function, toCharCode(s):

我们可以使用fromCharCode(n)将数字转换为字符串。要找到与字符对应的数值,我们需要它的反函数toCharCode(s)

var toCharCode = function(s){ return s.charCodeAt(0) } // 'a' => 97, 'b' => 98, ..

Then the rest is easy:

然后剩下的就很简单了:

Array.apply(null, {length: 26})
     .map(function (x,i) { return String.fromCharCode(97 + i) });

Constructs an array of 26 undefined's: [undefined, ... , undefined]. Then mapindex iof each value to 97 + i== 'a'.charCodeAt(0) + i(for uppercase start at 'A' => 65).

构造一个包含 26 个未定义的数组:[undefined, ... , undefined]。然后将每个值的map索引i设置为97 + i== 'a'.charCodeAt(0) + i(对于大写从 开始'A' => 65)。

This first line might need some explanation. What we are effectively doing is the same as Array(1,2,3)== [1,2,3]. Instead of passing an actual array to apply, we pass something that quacks like an array (has the lengthproperty). This results in calling Array(undefined, .. , undefined).

第一行可能需要一些解释。我们有效地做的与Array(1,2,3)==相同[1,2,3]apply我们没有将实际数组传递给,而是传递类似于数组(具有length属性)的东西。这导致调用Array(undefined, .. , undefined).

See applyand "generic array-like object"for more infomation.

apply“通用阵列状物体”的更多资料。

回答by Mark Thomas

CoffeeScriptcompiles to javascript, and it has numeric ranges:

CoffeeScript编译为 javascript,它具有数字范围:

(String.fromCharCode(x+64) for x in [1..26]).join(",")

Here's a linkto this script in the coffeescript.org site. You can see what javascript it compiles to, and run it in your browser live.

这是在 coffeescript.org 站点中指向此脚本的链接。你可以看到它编译成什么 javascript,并在你的浏览器中实时运行它。

(And yes, you can use coffeescript for Node.js)

是的,您可以将 coffeescript 用于 Node.js)

回答by test30

Slightly different approach

略有不同的做法

String.fromCharCode(..." ".repeat(26).split("").map((e,i)=>i+'A'.charCodeAt()))

prints

印刷

"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

回答by Anatoliy Arkhipov

Maybe this function will help you.

也许这个功能会对你有所帮助。

function range ( low, high, step ) {    // Create an array containing a range of elements
    // 
    // +   original by: _argos

    var matrix = [];
    var inival, endval, plus;
    var walker = step || 1;
    var chars  = false;

    if ( !isNaN ( low ) && !isNaN ( high ) ) {
        inival = low;
        endval = high;
    } else if ( isNaN ( low ) && isNaN ( high ) ) {
        chars = true;
        inival = low.charCodeAt ( 0 );
        endval = high.charCodeAt ( 0 );
    } else {
        inival = ( isNaN ( low ) ? 0 : low );
        endval = ( isNaN ( high ) ? 0 : high );
    }

    plus = ( ( inival > endval ) ? false : true );
    if ( plus ) {
        while ( inival <= endval ) {
            matrix.push ( ( ( chars ) ? String.fromCharCode ( inival ) : inival ) );
            inival += walker;
        }
    } else {
        while ( inival >= endval ) {
            matrix.push ( ( ( chars ) ? String.fromCharCode ( inival ) : inival ) );
            inival -= walker;
        }
    }

    return matrix;
}

console.log(range('A','Z')) 
// ["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"]

This is not mine, taken from: http://javascript.ru/php/range

这不是我的,取自:http: //javascript.ru/php/range

回答by Phrogz

No, JavaScript does not have any built-in Range object. You would need to write a function to create an abstract Range, and then add a to_amethod for the equivalence.

不,JavaScript 没有任何内置的 Range 对象。您需要编写一个函数来创建一个抽象的 Range,然后添加一个to_a等价的方法。

For fun, here's an alternative way to get that exact output, with no intermediary strings.

为了好玩,这里有另一种方法来获得准确的输出,没有中间字符串。

function commaRange(startChar,endChar){
  var c=','.charCodeAt(0);
  for (var a=[],i=startChar.charCodeAt(0),e=endChar.charCodeAt(0);i<=e;++i){
    a.push(i); a.push(c);
  }
  a.pop();
  return String.fromCharCode.apply(String,a);
}

console.log(commaRange('A','J')); // "A,B,C,D,E,F,G,H,I,J"

For Node.js, there is the Lazymodule.

对于 Node.js,有Lazy模块。

回答by Diode

function range(r, x) {
    var c1 = r.charCodeAt(0)+1, c2 = r.charCodeAt(3), s = r[0];
    if(c1 && c2)while (c1 <= c2) s += (x || "") + String.fromCharCode(c1++);
    return s;
}

range("A--S", ",");