@ each loop with index

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

我有以下的代码,但我想知道是否 $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;
}
}
44455 次浏览

首先,@each函数不是来自 Compass,而是来自 Sass。


为了回答你的问题,这不能用 each 循环完成,但是很容易将其转换成 @for循环,它可以这样做:

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


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

为了更新这个答案: 是的,你可以通过 @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/

有时你可能需要使用一个数组或映射,我有一个数组数组,比如:

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

我发现把它转换成一个物体是最简单的:

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

使用以下方法得到 $i:

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

Sass 团队还推荐了以下几点,虽然我不是很喜欢:

[ ... ]以上代码是我想解决这个问题的方式。可以通过添加 Sass 函数(如 range ($n))来提高效率。所以范围(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));
}

链接。