首页 > 解决方案 > Sass:仅返回具有唯一字符的列表值

问题描述

任何人都可以提供一个函数来从列表中返回不包含重复字符的值吗?

例如,假设我的列表值为$list: (aa, bb, cd, ef);

预期输出:

(cd, 英孚);

这是我到目前为止得到的代码。它根本不能解决我的问题,但经过多次试验,这就是我所能得到的。

@function dupChars($list, $separator: comma) {

  $result: null;
  $temp: null;

  @each $item in $list {

    @for $i from 1 through str-length($item) {

      @if not index($temp, str-slice($item, $i, $i)) {

        $temp: append($temp, #{str-slice($item, $i, $i)}, $separator);
      }
    }
  }

  $result: append($result, $temp, $separator);

  @return $result;
}

$list: (aa, bb, cd, ef);

/* #{dupChars($list)} */

获得的输出:

a, b, c, d, e, f

标签: sass

解决方案


为了解决这个问题,我发现一种方法可以检查每个项目中有多少相同的单个字母(使用双@for循环)。

例如,假设有这个列表:abc. 如果结果是 3(我的项目的长度),我知道每个字母在该项目中只有一次,那么就没有重复项 (3 = 3)。

a -- a // 1
a -- b
a -- c
b -- a
b -- b // 2
b -- c
c -- a
c -- b
c -- c // 3

另一个例子。现在我们的清单是aab. 结果大于我的项目的长度,所以我们有重复项 (5 > 3)

a -- a // 1
a -- a // 2
a -- b 
a -- a // 3
a -- a // 4
a -- b
b -- a
b -- a
b -- b // 5

因此,当数字大于我的项目长度时,我不会将其附加$temp到我的$result

编码:

@function dupChars($list, $separator: comma) {
    $result: null;
    $temp: null;

    @each $item in $list {
        $var: 0;
        @for $i from 1 through length($item) {

            @for $j from 1 through (str-length($item)) {

                @for $k from 1 through (str-length($item)) {
                    //@debug str-slice($item, $j, $j) + "---" + str-slice($item, $k, $k) ;

                    @if (str-slice($item, $j, $j) == str-slice($item, $k, $k)) {
                        $var: $var + 1;
                    }
                }
            }
        }
        @if($var <= str-length($item)){
          $temp: append($temp, #{$item}, $separator);
        }
    }

    $result: append($result, $temp, $separator);

    @return $result;
}

$lista: (aa, bb, cd, ef);

div{content: dupChars($lista)};

输出:

div {
  content: cd, ef;
}

推荐阅读