2013-02-28 111 views
47

我想知道你是否可以得到@each循环的元素索引。@index循环索引

我有以下代码,但我想知道$i变量是否是最好的方法来做到这一点。

当前代码:

所有的
$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; 
    } 
} 

回答

70

首先,@each功能并非来自指南针,而是来自萨斯。


要回答你的问题,这不能与每一个循环来完成,但很容易将它转换成@for环,它可以这样做:

@for $i from 1 through length($refcolors) { 
    $c: nth($refcolors, $i); 

    // ... do something fancy with $c 
} 
+0

甜。谢谢:D – ignacioricci 2013-02-28 22:30:58

+9

imho,当使用'each'时,sass作者应该自动创建一个'$ idx'变量,它将被用作索引。这非常有用。 – vsync 2014-12-14 10:48:37

40

要更新这个答案:是的,你可以用@each循环实现这一目标:

$colors-list: #111 #222 #333 #444 #555; 

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

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

+11

不幸的是,如果$ colors-list包含2个相同的值(例如#111,#222,#111,#333),则这种方法会中断。在这种情况下,索引($ colors-list,#111)将始终返回1,所以您的$ i值将以1,2,1,4的形式出现。否则,这是一个非常整洁的方法:) – Joel 2014-11-18 20:51:22

+1

这也是1索引而不是普通的0-索引 – 2016-02-11 08:17:37

4

有时您可能需要使用数组或地图。我有一个数组的数组,即:

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

我发现,这是最简单的,只是它转换成一个对象:

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

,并使用以下获得$i

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

sass团队还推荐以下内容,虽然我并不是很多粉丝:

[...]上面的代码是我想解决这个问题的方法。通过添加一个像范围($ n)这样的Sass函数可以提高效率。因此,范围(10)=>(1,2,3,4,5,6,7,8,9,10)。然后枚举可以成为:

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

link.