@each loop with index

后端 未结 3 813
渐次进展
渐次进展 2020-12-23 14:23

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 t

相关标签:
3条回答
  • 2020-12-23 14:55

    To update this answer: yes you can achieve this with the @each loop:

    $colors-list: #111 #222 #333 #444 #555;
    
    @each $current-color in $colors-list {
        $i: index($colors-list, $current-color);
        .stuff-#{$i} { 
            color: $current-color;
        }
    }
    

    Source: http://12devs.co.uk/articles/handy-advanced-sass/

    0 讨论(0)
  • 2020-12-23 15:01

    Sometimes you may need to use an array or a map. I had an array of arrays, i.e.:

    $list = (('sub1item1', 'sub1item2'), ('sub2item1', 'sub2item2'));
    

    I found that it was easiest to just convert it to an object:

    $list: (
        'name': 'thao',
        'age': 25,
        'gender': 'f'
    );
    

    And use the following to get $i:

    @each $property, $value in $list {
        $i: index(($list), ($property $value));
    

    The sass team also recommended the following, although I'm not much of a fan:

    [...] The above code is how I'd like to address this. It can be made more efficient by adding a Sass function like range($n). So that range(10) => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). Then enumerate can become:

    @function enumerate($list-or-map) {
        @return zip($list-or-map, range(length($list-or-map));
    }
    

    link.

    0 讨论(0)
  • 2020-12-23 15:15

    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
    }
    
    0 讨论(0)
提交回复
热议问题