How to loop through the alphabet via underscoreJS

2020-03-01 05:56发布

问题:

I'm using Underscore's template() method in BackboneJS views. I'd like to show a list of alphabet letters in my view in order to sort a collection by letter.

As a result, I have a list of 26 links (one link = one letter) in my view. Instead of copy-pasting each link (which is very bad for code maintainability), I was wondering if it was possible to loop through the alphabet via underscoreJS.

Result to display :

<li ><a href="#">a</a></li>
<li ><a href="#">b</a></li>
<li ><a href="#">c</a></li>
...
<li ><a href="#">z</a></li>

回答1:

var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
_.each(alphabet, function(letter) {
  console.log(letter);
});

That's how you could do it.



回答2:

  1. Create a range with the charcodes

    var alphas = _.range(
        'a'.charCodeAt(0),
        'z'.charCodeAt(0)+1
    ); 
    // [97 .. 122]
    
  2. Create an array with the letters

    var letters = _.map(alphas, a => String.fromCharCode(a));
    // see @deefour comment
    
    // Non ES6 version
    // var letters = _.map(alphas, function(a) {
    //    return String.fromCharCode(a);
    // });
    
    // [a .. z]
    
  3. Inject into your template

    var tpl = 
    '<ul>'+
        '<% _.each(letters, function(letter) { %>'+
            '<li><%= letter %></li>'+
        '<% }); %>'+
    '</ul>';
    var compiled = _.template(tpl);
    var html = compiled({letters : letters});
    

And a demo http://jsfiddle.net/hPdSQ/17/

var alphas = _.range(
    'a'.charCodeAt(0),
    'z'.charCodeAt(0)+1
); 

var letters = _.map(alphas, a => String.fromCharCode(a));

var tpl = 
'<ul>'+
    '<% _.each(letters, function(letter) { %>'+
        '<li><%= letter %></li>'+
    '<% }); %>'+
'</ul>';
var compiled = _.template(tpl);

var html = compiled({letters : letters});

document.getElementById('res').innerHTML = html;
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id='res'></div>



回答3:

for(var letter=65;letter<91;letter++)
{
var _char = String.fromCharCode(letter);
console.log(_char);
}

or use from 97 - 123 ascii code for lowercase letters



回答4:

for (var i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
  console.log(String.fromCharCode(i));
}



回答5:

Using ES6 for-of:

for(let char of "abcdefghijklmnopqrstuvwxyz" )
  console.log(char); // prints 'a' to 'z'
   

Pretty easy to use that in a template, and you could use Babel to transpile it to code for browsers which lack support for that syntax.



回答6:

Another approach with underscore (or loadash):

_.map(_.range(26), function(i) { return String.fromCharCode(97 + i) });

// returns ['a', 'b', ..., 'z']


回答7:

Using underscore.js and jQuery in conjunction will help you acheive this (underscore.js is incapable of doing DOM insertion/manipulation by itself).

var abc = ['a', 'b', 'c', 'd']; //i disregarded how you get the list of letters.

_.each(abc, function(letter){
    $('ul').append('<li><a href="#">'+letter+'</a></li>');
});

Also made a fiddle for you



回答8:

Underscore don't have such ability, but your case could do some trick on the template. change your template like this:

<% for(var i=65; i<90; i++) { %>
<li ><a href="#"><% print(String.fromCharCode(i)); %></a></li>
<% } %>

this should be what you want.



回答9:

Here's an improved* version of @Medo Medo's pure JS code:

    var letters=[], letter_first = 'a', letter_last = 'z' // you can also use A and Z
    for (var letter=letter_first.charCodeAt(0);letter<=letter_last.charCodeAt(0);letter++)
      letters.push(String.fromCharCode(letter))
    document.write(letters.join(''))

  • Fixed the "var" declaration
  • Added direct letter detection
  • Collected the result into an array in order to have only one output
  • Made the code runnable right here