【问题标题】:Why doesn't Sass `map-get()` return an error for a non-existent key?为什么 Sass `map-get()` 不为不存在的键返回错误?
【发布时间】:2015-11-03 21:25:48
【问题描述】:

为什么在提供的映射中不存在键时map-get() 不抛出错误?

例如:

$map: (
  'keyone': 'value',
  'keytwo': 'value',
  'keythree': 'value'
);

map-get($map, 'keyfour');

我知道map-has-key() 并且我知道它本身可能有用,但如果我想顺利使用map-get(),我不应该每次都调用map-has-key()。我希望map-get() 会引发错误,但它会默默地失败。为什么这没有内置到 Sass 中?

如果重要的话,我使用的是 node-sass 3.2.0。

【问题讨论】:

    标签: sass node-sass


    【解决方案1】:

    map-get() 返回null 而不是在映射中找不到键时引发错误的行为是设计使然。来自 Sass 的维护者(关于为什么 nth() 在请求缺少的元素时会抛出错误,而 map-get() 不会):

    一般来说,当代码出错时尽早抛出错误是好的。超出范围的列表访问很可能是意外且不正确的;相比之下,地图中缺少的键更有可能是有目的的。

    通过https://github.com/sass/sass/issues/1721

    我碰巧不同意nex3(map-get()应该抛出一个错误,或者至少抛出一个可以被抑制的警告)。您可以通过编写自己的自定义 map-get 函数来获得所需的行为:

    @function map-get-strict($map, $key) {
        @if map-has-key($map, $key) {
            @return map-get($map, $key);
        } @else {
            @error "ERROR: Specified index does not exist in the mapping";
        }   
    }
    
    $map:
      ( one: 1
      , two: 2
      );
    
    .foo {
      test1: map-get-strict($map, one); // returns the expected value of `1`
      test2: map-get-strict($map, three); // raises an error
    }
    

    【讨论】:

    • 不错。该错误不会显示您出错的地方。这也可能吗?
    • 例如哪个文件名
    • 只是为了完成,@error 默认情况下应该已经提供了该信息:sass-lang.com/documentation/at-rules/error
    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多