Why doesn't Sass `map-get()` return an error for a non-existent key?

房东的猫 提交于 2019-12-10 17:51:08

问题


Why doesn't map-get() throw an error when the key does not exist in the supplied map?

For example:

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

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

I'm aware of map-has-key() and I understand that might be useful on its own, but if I want to use map-get() smoothly, I shouldn't have to call map-has-key() each and every time. I'd expect the map-get() to throw an error, but instead it fails silently. Why is this not built into Sass?

If it matters, I'm using node-sass 3.2.0.


回答1:


The behavior of map-get() returning null rather than throwing an error when a key is not found in the mapping is by design. From the maintainer of Sass (on why nth() throws an error when requesting a missing element but map-get() does not):

In general, it's good to throw errors as early as possible when code is doing something wrong. It's very likely than an out-of-range list access is accidental and incorrect; by contrast, a missing key in a map is much more likely to be purposeful.

via https://github.com/sass/sass/issues/1721

I happen to disagree with nex3 on this (map-get() should throw an error, or at the very least throw a warning that can be suppressed). You can get your desired behavior by writing your own custom map-get function:

@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
}


来源:https://stackoverflow.com/questions/31945400/why-doesnt-sass-map-get-return-an-error-for-a-non-existent-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!