如何在Sass中于指定索引位置合并两个映射(Map)
在Sass映射指定索引位置合并另一个映射的解决方案
Sass原生的map.merge()仅支持将新映射追加到目标映射末尾,要实现指定索引位置的合并,需要借助映射与列表的转换来完成。以下是自定义实现方案:
自定义合并函数
@function map-insert-at-index($target-map, $insert-map, $insert-position) { // 将映射转换为键值对列表(每个子项格式为 (key, value)) $target-pairs: map-pairs($target-map); $insert-pairs: map-pairs($insert-map); // 拆分目标列表为插入位置前后的两部分 $before: list-slice($target-pairs, 1, $insert-position - 1); $after: list-slice($target-pairs, $insert-position); // 拼接列表并转回映射 return map-from-pairs(list.join($before, list.join($insert-pairs, $after))); }
结合你的示例使用
$numbers: ( "one": 1, "two": 2, "three": 3, "six": 6, "seven": 7, ); $more-numbers: ( "four": 4, "five": 5, ); // 定位"three"对应的键值对位置,计算插入索引(插入到它之后) $target-pair: ("three", 3); $insert-index: list.index(map-pairs($numbers), $target-pair) + 1; // 执行指定位置合并 $merged-numbers: map-insert-at-index($numbers, $more-numbers, $insert-index); // 输出结果符合预期:("one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7) @debug $merged-numbers;
适配你的实际业务需求
针对生成工具类的场景,你可以直接定位到关键词类(如auto)对应的键值对,计算插入索引后将数值类映射插入到它之前:
// 假设你的工具类映射包含关键词类 $utils-map: ( "w-1": 25%, "w-2": 50%, "w-auto": auto, "w-full": 100% ); // 动态生成的数值类映射 $dynamic-utils: ( "w-3": 75%, "w-4": 100% ); // 定位"w-auto"的位置,插入到它之前 $target-pair: ("w-auto", auto); $insert-index: list.index(map-pairs($utils-map), $target-pair); $final-utils: map-insert-at-index($utils-map, $dynamic-utils, $insert-index);
这样生成的CSS中,数值类工具会先于关键词类输出,利用CSS同权重下后定义样式覆盖先定义的特性,确保关键词类能正确生效,同时无需拆分原有映射,避免响应式类生成逻辑混乱。
关键API说明
map-pairs($map):将映射转为键值对列表,保留原有顺序map-from-pairs($list):将键值对列表转回映射list-slice($list, $start, $end):截取列表的指定片段list.index($list, $value):查找目标值在列表中的索引(从1开始计数)
内容的提问来源于stack exchange,提问作者apsuhos
相关产品推荐
相关产品推荐

