Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@each loop with index

Tags:

each

sass

I was wondering if you can get an element index for the @each loop.

I have the following code, but I was wondering if the $i variable was the best way to do this.

Current code:

$i: 0; $refcolors: #55A46A, #9BD385, #D9EA79, #E4EE77, #F2E975, #F2D368, #F0AB55, #ED7943, #EA4E38, #E80D19;  @each $c in $refcolors {     $i: $i + 1;     #cr-#{$i} strong {         background:$c;     }    } 
like image 343
ignacioricci Avatar asked Feb 28 '13 22:02

ignacioricci


People also ask

How do I keep track of index in for loop?

To check the index in for loop you can use enumerate() function. In Python, the enumerate() is an in-built function that allows us to loop over a list and count the number of elements during an iteration with for loop.

Does forEach have an index?

C#'s foreach loop makes it easy to process a collection: there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach .

How do I get an index in forEach?

With the later C# versions so you also use tuples, so you'll have something like this: foreach (var (item, i) in Model. Select((v, i) => (v, i))) Allows you to access the item and index (i) directly inside the for-loop with tuple deconstruction.


1 Answers

First of all, the @each function is not from Compass, but from Sass.


To answer your question, this cannot be done with an each loop, but it is easy to convert this into a @for loop, which can do this:

@for $i from 1 through length($refcolors) {     $c: nth($refcolors, $i);      // ... do something fancy with $c } 
like image 74
Wouter J Avatar answered Oct 05 '22 18:10

Wouter J