Create an array of characters from specified range

后端 未结 12 2180
名媛妹妹
名媛妹妹 2020-12-17 08:19

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         


        
相关标签:
12条回答
  • 2020-12-17 08:44
    var range = [];
    for(var i = 65; i < 91; i++)
    {
     range.push(String.fromCharCode(i));
    }
    range = range.join(',');
    

    gives range a-z, but i like the function option of some too.

    0 讨论(0)
  • 2020-12-17 08:47

    https://stackoverflow.com/a/64599169/8784402

    Generate Character List with one-liner

    const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));
    
    console.log("from A to G", charList('A', 'G'));
    console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
    console.log("reverse order from Z to P", charList('Z', 'P', -1));
    console.log("from 0 to 5", charList('0', '5', 1));
    console.log("from 9 to 5", charList('9', '5', -1));
    console.log("from 0 to 8 with step 2", charList('0', '8', 2));
    console.log("from α to ω", charList('α', 'ω'));
    console.log("Hindi characters from क to ह", charList('क', 'ह'));
    console.log("Russian characters from А to Я", charList('А', 'Я'));

    For TypeScript
    const charList = (p: string, q: string, d = 1) => {
      const a = p.charCodeAt(0),
        z = q.charCodeAt(0);
      return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
        String.fromCharCode(a + i * d)
      );
    };
    
    0 讨论(0)
  • 2020-12-17 08:51

    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

    0 讨论(0)
  • 2020-12-17 08:55

    CoffeeScript compiles to javascript, and it has numeric ranges:

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

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

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

    0 讨论(0)
  • 2020-12-17 08:55

    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_a method for the equivalence.

    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 Lazy module.

    0 讨论(0)
  • 2020-12-17 08:56

    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));
    
    0 讨论(0)
提交回复
热议问题