从Sass映射中获取编号,而不是字符串

从Sass映射中获取编号,而不是字符串,sass,mixins,Sass,Mixins,我正在构建一个sass mixin,根据从地图上得到的值进行计算。这是我在这张地图上看到的: $icons: ( search: 1, arrow: 2, home: 3 ); 还有这个mixin(这个帖子简化了): 现在,当我编译这个时,我得到一个错误,因为来自映射的值不是一个数字,而是一个字符串。因此,在本例中,值2是一个字符串。我找到了一种方法,通过使用以下命令将其更改为数字: @function number($value) { @if type-of($value)

我正在构建一个sass mixin,根据从地图上得到的值进行计算。这是我在这张地图上看到的:

$icons: (
  search: 1,
  arrow: 2,
  home: 3
);
还有这个mixin(这个帖子简化了):

现在,当我编译这个时,我得到一个错误,因为来自映射的值不是一个数字,而是一个字符串。因此,在本例中,值2是一个字符串。我找到了一种方法,通过使用以下命令将其更改为数字:

@function number($value) {
  @if type-of($value) == 'number' {
    @return $value;
  } @else if type-of($value) != 'string' {
    $_: log('Value for `to-number` should be a number or a string.');
  }

  $result: 0;
  $digits: 0;
  $minus: str-slice($value, 1, 1) == '-';
  $numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);

  @for $i from if($minus, 2, 1) through str-length($value) {
    $character: str-slice($value, $i, $i);

    @if not (index(map-keys($numbers), $character) or $character == '.') {
      @return to-length(if($minus, -$result, $result), str-slice($value, $i))
    }

    @if $character == '.' {
      $digits: 1;
    } @else if $digits == 0 {
      $result: $result * 10 + map-get($numbers, $character);
    } @else {
      $digits: $digits * 10;
      $result: $result + map-get($numbers, $character) / $digits;
    }
  }

  @return if($minus, -$result, $result);;
}
然后:

@mixin addIcon($icon: 'arrow'){
  @if map-has-key($icons, $icon) {
     $posIcon: #{map-get($icons, $icon)};
     $posX: number($posIcon) * 48;
     @debug $posX;
  }
}

但我觉得必须有一个更简单的方法来做到这一点。如何确保映射中的值是一个数字而不是字符串?

您将字符串作为值,因为
映射得到的结果是
。如果删除插值,将得到一个数字:

@mixin addIcon($icon: 'arrow'){
  @if map-has-key($icons, $icon) {
     $posIcon: map-get($icons, $icon);
     $posX: $posIcon * 48;
     @debug $posX;
  }
}

我不知道你想做什么。您将
$icon
作为
'arrow'
(默认)发送,然后尝试执行
'arrow'*48
,这当然不起作用。它不应该是地图中箭头的值吗?所以
2*48
?是的,很抱歉我忘了代码的一个重要部分。我在原来的问题中改了。是的,它应该是箭头的值。
@mixin addIcon($icon: 'arrow'){
  @if map-has-key($icons, $icon) {
     $posIcon: map-get($icons, $icon);
     $posX: $posIcon * 48;
     @debug $posX;
  }
}