【问题标题】:Get number from Sass map instead of string从 Sass 映射中获取数字而不是字符串
【发布时间】:2020-02-07 07:37:26
【问题描述】:

我正在构建一个 sass mixin,在其中我根据从地图获得的值进行计算。这就是我拥有的这张地图:

$icons: (
  search: 1,
  arrow: 2,
  home: 3
);

还有这个 mixin(为这篇文章做了简化):

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

现在,当我编译它时,我得到一个错误,因为地图中的值不是数字而是字符串。所以在这种情况下,值 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;
  }
}

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

【问题讨论】:

  • 我不确定你想做什么。您将$icon 发送为'arrow'(默认情况下),然后尝试发送'arrow' * 48,这当然行不通。不应该是地图中箭头的值吗?那么2 * 48?
  • 是的,抱歉,我忘记了代码的重要部分。我在我原来的问题中改变了它。是的,它应该是箭头的值。

标签: sass mixins


【解决方案1】:

你得到一个字符串作为值,因为你interpolatemap-get 的结果。如果去掉插值,你会得到一个数字:

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

【讨论】:

    猜你喜欢
    • 2018-11-28
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2019-01-26
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多