Skip to content
On this page

迭代

Stylus 允许你通过 for/in 结构迭代表达式,其形式为:

bash
for <值名称> [, <键名称>] in <表达式>
for <值名称> [, <键名称>] in <表达式>

例如:

stylus
body
  for num in 1 2 3
    foo num
body
  for num in 1 2 3
    foo num

生成:

stylus
body {
  foo: 1;
  foo: 2;
  foo: 3;
}
body {
  foo: 1;
  foo: 2;
  foo: 3;
}

下面的示例展示了如何使用 <键名称>

stylus
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

生成:

css
body {
  foo: 0 Impact;
  foo: 1 Arial;
  foo: 2 sans-serif;
}
body {
  foo: 0 Impact;
  foo: 1 Arial;
  foo: 2 sans-serif;
}

以下是常规 for 循环的写法:

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

生成:

css
body {
  foo: 1;
  foo: 2;
  foo: 3;
  foo: 4;
  foo: 5;
}
body {
  foo: 1;
  foo: 2;
  foo: 3;
  foo: 4;
  foo: 5;
}

与字符串一起使用:

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

混合器

我们可以在混合器中使用迭代来产生强大的功能。例如,我们可以使用插值和迭代将表达式对作为属性应用。

下面我们定义 apply(),有条件地利用所有 arguments,以便支持逗号分隔和表达式列表:

stylus
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 循环。下面是一些使用示例:

求和:

stylus
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

连接:

stylus
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 也可以这样做。下面是上面的示例使用后缀语法:

stylus
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 时返回数字。

stylus
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

Released under the MIT License.