◆

Sass 比较与逻辑操作符(and、or、==)用法

2023-02-02 01:370

示例

Sass 里写条件判断(@if)和带默认值的函数时,绕不开一批比较和逻辑操作符。它们的写法看着和 JS 很像,但有两处行为差别足够让人写出「编译不报错、结果却不对」的样式,这篇就是把这些差别一次性验证清楚。

第一处是 and / or 的返回值:它们返回的不是布尔值,而是参与运算的那个值本身。false or 123 得到 123,456 and 123 得到 123。这正是 $name or default 这种「取默认值」写法能成立的原因。第二处是 Sass 的假值只有 false 和 null 两个,其它一切——包括空字符串、0、拼错的单词——都算真值。

以下代码主要用到了 and,or,>,!=,== 等操作符,其中的操作符比较的逻辑基本和 js 一致

需要注意的是,在 sass 中的 == 是严格的值相等判断,不做任何隐式类型转换,也没有 JS 里 == 那套宽松比较规则。所以 false == null 的结果是 false——两者都是假值,但它们是不同的值。

这段把各种组合都摆出来当测试用例。开头的 name 函数演示了 or 的兜底用法:匹配不上时把 $name 置为 false,@return $name or default 这一步 false 就被替换成了 default,等价于「没值时取默认值」。

后面 .test 里那一长串声明是操作符逐个求值的结果。留意 t-a-f: true and fasle 这条,fasle 是拼错的单词,Sass 把它当成一个普通标识符(真值)处理,于是 and 直接返回了它,编译产物里就出现了 fasle 这个字符串——拼写错误不会报错,只会静默产出错误的 CSS。

@function name($name) {
  @if $name == 'wfly' {
    $name: wfly;
  } @else {
    $name: false;
  }
  @return $name or default;
}

.test {
  name: name('wfly');
  name-one: name('no');
  t-a-f: true and fasle;
  f-a-t: false and true;
  t-a-t: true and true;
  t-o-f: true or false;
  f-o-t: false or true;
  true-str: false or 123;
  true-str-one: 456 and 123;
  true-str-two: 456 and false;
  true-str-three: false == false;
  true-str-four: true != false;
  true-str-five: 10 > 1;
  true-str-six: -1 > 1;
  true-str-seven: false == null;
  true-str-eight: false == undefined;
  true-str-nine: false == NaN;
}

编译后

对照编译结果看几个关键点:true-str: 123(or 返回的是值不是布尔)、true-str-two: false(and 遇到假值返回该假值)、true-str-seven/eight/nine 全是 false(null、undefined、NaN 都不等于 false,其中 undefined 和 NaN 在 Sass 里根本不是特殊值,只是普通标识符)。

.test {
  name: wfly;
  name-one: default;
  t-a-f: fasle;
  f-a-t: false;
  t-a-t: true;
  t-o-f: true;
  f-o-t: true;
  true-str: 123;
  true-str-one: 123;
  true-str-two: false;
  true-str-three: true;
  true-str-four: true;
  true-str-five: true;
  true-str-six: false;
  true-str-seven: false;
  true-str-eight: false;
  true-str-nine: false;
}
💬留言板0

还没有留言,来发表第一条吧~

PAGE LOAD / LIVESass 比较与逻辑操作符(and、or、==)用法加载中