Create an array of characters from specified range

后端 未结 12 2214
名媛妹妹
名媛妹妹 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: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

提交回复
热议问题