反覆
Stylus 允許您透過 for/in
結構反覆表達式,其形式為
for <val-name> [, <key-name>] in <expression>
for <val-name> [, <key-name>] in <expression>
例如
body
for num in 1 2 3
foo num
body
for num in 1 2 3
foo num
產生
body {
foo: 1;
foo: 2;
foo: 3;
}
body {
foo: 1;
foo: 2;
foo: 3;
}
以下範例顯示如何使用 <key-name>
body
fonts = Impact Arial sans-serif
for font, i in fonts
foo i font
body
fonts = Impact Arial sans-serif
for font, i in fonts
foo i font
產生
body {
foo: 0 Impact;
foo: 1 Arial;
foo: 2 sans-serif;
}
body {
foo: 0 Impact;
foo: 1 Arial;
foo: 2 sans-serif;
}
以下是如何執行一般 for 迴圈
body
for num in (1..5)
foo num
body
for num in (1..5)
foo num
產生
body {
foo: 1;
foo: 2;
foo: 3;
foo: 4;
foo: 5;
}
body {
foo: 1;
foo: 2;
foo: 3;
foo: 4;
foo: 5;
}
與字串一起使用
for num in (1..10)
.box{num}
animation: box + num 5s infinite
@keframes box{num}
0% { left: 0px }
100% { left: (num * 30px) }
for num in (1..10)
.box{num}
animation: box + num 5s infinite
@keframes box{num}
0% { left: 0px }
100% { left: (num * 30px) }
混合
我們可以在 mixin 內使用迭代來產生強大的功能。例如,我們可以使用插值和迭代將表達式對應用作屬性。
以下我們定義 apply()
,有條件地使用所有 arguments
,以便支援逗號分隔的和表達式清單
apply(props)
props = arguments if length(arguments) > 1
for prop in props
{prop[0]} prop[1]
body
apply(one 1, two 2, three 3)
body
list = (one 1) (two 2) (three 3)
apply(list)
apply(props)
props = arguments if length(arguments) > 1
for prop in props
{prop[0]} prop[1]
body
apply(one 1, two 2, three 3)
body
list = (one 1) (two 2) (three 3)
apply(list)
函式
Stylus 函式也可以包含 for 迴圈。以下是部分範例用途
總和
sum(nums)
sum = 0
for n in nums
sum += n
sum(1 2 3)
// => 6
sum(nums)
sum = 0
for n in nums
sum += n
sum(1 2 3)
// => 6
加入
join(delim, args)
buf = ''
for arg, index in args
if index
buf += delim + arg
else
buf += arg
join(', ', foo bar baz)
// => "foo, bar, baz"
join(delim, args)
buf = ''
for arg, index in args
if index
buf += delim + arg
else
buf += arg
join(', ', foo bar baz)
// => "foo, bar, baz"
後綴
很像 if
/ unless
可以用於陳述式之後,for
也可以這樣做。以下是使用後綴語法的相同範例
sum(nums)
sum = 0
sum += n for n in nums
join(delim, args)
buf = ''
buf += i ? delim + arg : arg for arg, i in args
sum(nums)
sum = 0
sum += n for n in nums
join(delim, args)
buf = ''
buf += i ? delim + arg : arg for arg, i in args
我們也可以在迴圈內傳回,以下是當 n % 2 == 0
評估為 true 時傳回數字的範例。
first-even(nums)
return n if n % 2 == 0 for n in nums
first-even(1 3 5 5 6 3 2)
// => 6
first-even(nums)
return n if n % 2 == 0 for n in nums
first-even(1 3 5 5 6 3 2)
// => 6