Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through the alphabet via underscoreJS

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>
like image 898
JeremyW Avatar asked May 28 '13 09:05

JeremyW


People also ask

How does_ each work?

each. The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.


1 Answers

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

That's how you could do it.

like image 135
jakee Avatar answered Nov 09 '22 16:11

jakee