我正在编写一个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
? - Arkellys