Create an array of characters from specified range

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

提交回复
热议问题