compact
从数组中删除所有 nil
值。
在此示例中,假设 site.pages
是网站内容页面的数组,其中一些页面具有名为 category
的属性,用于指定其内容类别。 如果我们将这些类别 map
到一个数组,如果任何页面没有 category
属性,则数组中的某些项可能是 nil
。
输入
{% assign site_categories = site.pages | map: "category" %}
{% for category in site_categories %}
- {{ category }}
{% endfor %}
输出
- business
- celebrities
-
- lifestyle
- sports
-
- technology
通过在我们创建 site_categories
数组时使用 compact
,我们可以删除数组中的所有 nil
值。
输入
{% assign site_categories = site.pages | map: "category" | compact %}
{% for category in site_categories %}
- {{ category }}
{% endfor %}
输出
- business
- celebrities
- lifestyle
- sports
- technology