JS中的二元操作符及三元操作符

1、二元操作符

二元操作符又叫二元逻辑运算符,是典型的基于boolean(逻辑)值的运算,他们返回的是boolean值。
二元运算符主要包括:

  • &&运算符 表示逻辑 与(and)
    使用规则:如:a&&b
    如果a为true,直接返回b;
    如果a为false,直接返回a;
console.log(1 && 2); //输出结果为2
console.log(1 && 2 && "new"); //输出结果为new
console.log(1 && 2 && 0 && "new"); //输出结果为0
console.log((1 && 2 || 0) && 4); //输出结果为4
  • || 运算符 表示逻辑 或(or)
    使用规则: 如:a||b
    如果a为true,直接返回a;
    如果a为false,直接返回b;
console.log(1||0); //输出结果为1
console.log(1 && 2 || 3 && 4); //输出结果为2

注:&&优先级高于 ||
二元布尔操作符是可进行短路操作的,只有再必要的时候才会计算到最后一项.

// 不推荐//
function foo(opt_win) {
  var win;
  if (opt_win) {
    win = opt_win;
  } else {
    win = window;
  }
  //...
}
//推荐写法//
function foo(opt_win) {
  var win = opt_win || window;
  // ...
}
//不推荐//
if (node) {
  if (node.kids) {
    if (node.kids[index]) {
      foo(node.kids[index]);
    }
  }
}
//推荐写法//
var kid = node && node.kids && node.kids[index];
if (kid) {
  foo(kid);
}

2、三元操作符

三元操作符又叫条件运算符,它将两个结果中其中一个符合运算逻辑的值返回。
三元运算符一般用于替代if条件判断语句。

  • 语法规则

    条件?表达式1:表达式2

    表示若条件成立(值为true),则返回表达式1,否则返回表达式2;

// 不推荐
if (val != 0) {
  return foo();
} else {
  return bar();
}

// 推荐
return val ? foo() : bar();
var msg = '数字' + n + '是' + (n % 2 === 0 ? '偶数' : '奇数');

3、注意事项

操作符始终写在前一行,以免分号的隐式插入产生预想不到的问题,正确的书写方式如下所示:

var x = a ? b : c;

var y = a ?
    longButSimpleOperandB : longButSimpleOperandC;

var z = a ?
        moreComplicatedB :
        moreComplicatedC;
参考文献:

https://www.w3cschool.cn/webdevelopment/jpbfrozt.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容