---
id: 587d7dbf367417b2b2512bba
title: Use @each to Map Over Items in a List
challengeType: 0
videoUrl: ''
localeTitle: 使用@each映射列表中的项目
---
## Description
最后一个挑战显示了@for
指令如何使用起始值和结束值循环一定次数。 Sass还提供了@each
指令,它循环遍历列表或映射中的每个项目。在每次迭代时,变量将从列表或映射分配给当前值。 @each $颜色为蓝色,红色,绿色{
。#{$ color} -text {color:$ color;}
}
地图的语法略有不同。这是一个例子: $ colors:(color1:blue,color2:red,color3:green);
@each $ key,$ colors in colors {
。#{$ color} -text {color:$ color;}
}
请注意,需要$key
变量来引用地图中的键。否则,编译后的CSS将有color1
, color2
...在里面。以上两个代码示例都转换为以下CSS: .blue-text {
颜色:蓝色;
}
.red-text {
红色;
}
.green-text {
颜色:绿色;
}
## Instructions
编写一个@each
列表的@each
指令: blue, black, red
,并将每个变量分配给.color-bg
类,其中“颜色”部分为每个项目更改。每个类应该将background-color
设置为相应的颜色。
## Tests
```yml
tests:
- text: 您的代码应该使用@each
指令。
testString: 'assert(code.match(/@each /g), "Your code should use the @each
directive.");'
- text: 您的.blue-bg
类应该具有蓝色的background-color
。
testString: 'assert($(".blue-bg").css("background-color") == "rgb(0, 0, 255)", "Your .blue-bg
class should have a background-color
of blue.");'
- text: 你的.black-bg
类的background-color
为黑色。
testString: 'assert($(".black-bg").css("background-color") == "rgb(0, 0, 0)", "Your .black-bg
class should have a background-color
of black.");'
- text: 您的.red-bg
类应该具有红色的background-color
。
testString: 'assert($(".red-bg").css("background-color") == "rgb(255, 0, 0)", "Your .red-bg
class should have a background-color
of red.");'
```
## Challenge Seed
## Solution
```js
// solution required
```