跳到正文

循环 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 对列表中的每一项或范围中的每个数字,重复页面的一部分。

yaml
# Recipe: q:loop over a list, a range of numbers and comma-separated text.
paths:
  components: ./components

type="array" 遍历一个列表,index= 给从 0 开始的位置命名。 type="range" 从 from 数到 to(两端都包含),步长为 step。 type="list" 按逗号拆分文本,并去掉每一项两端的空格。

xml
<q:component name="Loops">
  <q:set name="fruits" type="array" value='["Apple", "Banana", "Cherry"]' />

  <html>
  <body>
    <h2>A list</h2>
    <ol>
      <!-- index= names the position, from 0 -->
      <q:loop type="array" var="fruit" index="i" items="{fruits}">
        <li>{i + 1}. {fruit}</li>
      </q:loop>
    </ol>

    <h2>A range</h2>
    <p>
      <!-- from and to are both included -->
      <q:loop type="range" var="n" from="2" to="10" step="2">
        <span>[{n}]</span>
      </q:loop>
    </p>

    <h2>Text split by commas</h2>
    <ul>
      <q:loop type="list" var="tag" items="red, green , blue">
        <li>({tag})</li>
      </q:loop>
    </ul>
  </body>
  </html>
</q:component>
xml
<q:test name="a list, with each position" page="/">
  <test:visit />
  <test:expect text="1. Apple" />
  <test:expect text="3. Cherry" />
</q:test>

<q:test name="a range includes both ends" page="/">
  <test:visit />
  <test:expect text="[2] [4] [6] [8] [10]" />
</q:test>

<q:test name="list items lose the spaces around them" page="/">
  <test:visit />
  <test:expect text="(red) (green) (blue)" />
</q:test>
text
tests/loops.test.q
  PASS  a list, with each position
  PASS  a range includes both ends
  PASS  list items lose the spaces around them
3 passed, 0 failed

要遍历查询结果的行,参见一个页面上的多个表单。 规则:LOOP-5 和 LOOP-6。

MIT 许可证 · 使用 VitePress 构建