Skip to content
On this page

循环迭代(Iteration)

Stylus允许你通过for/in对表达式进行迭代,形式如下:

for <val-name> [, <key-name>] in <expression>
for <val-name> [, <key-name>] in <expression>

For example:

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;
}

And here's how you do a regular for loop

body
  for num in (1..5)
    foo num
body
  for num in (1..5)
    foo num

Yields:

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) }

混合(Mixins)

我们可以在混合中使用循环实现更强大的功能,例如,我们可以把表达式对作为使用插值和循环的属性。

下面,我们定义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)

函数(Functions)

Stylus函数同样可以包含for循环。下面就是简单使用示例:

Sum:

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:

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"

后缀(Postfix)

就跟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 == 0true的时候返回数值。

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