javascript运算符(常用的)

【1】算术运算符

     1)、加法运算符(+):

  //数字加数字
  alert(1 + 2 + 3);

  //数字加对象
  alert(1 + [2] + [3]);

  //数字加字符串
  alert(1 + 2 + 3 + ' = 1 + 2 + 3');
  alert('1 + 2 + 3 = ' + 1 + 2 + 3);

  //字符串加字符串
  alert('1 + 2 + 3 = ' + '6');

     2)、减法运算符(-):

  //数字减数字
  alert(6 - 3 - 2);

  //数字减对象
  alert(6 - [3] - [2]);

  //数字减字符串
  alert(6 - 3 - 2 + ' = 6 - 3 - 2');
  alert('6 - 3 - 2 = ' + 6 - 3 - 2);

     3)、递增运算符(++):

  //前置递增
  var a = [1];
  var b = ++a;

  alert(a);  //2
  alert(b);  //2

  //后置递增
  var a = '1';
  var b = a++;

  alert(a);  //2
  alert(b);  //1

根据几个例子我们得出结论,JavaScript 中的算术运算符,会尝试将其它类型转换为数字再运算,如果转换失败会变成特殊值 NaN 。

此外,加法运算符还可以连接字符串,此时它会优先考虑将其它类型转为字符串。

【2】相等运算符

     1)、相等运算符(==):

//这些例子可以证明,相等运算符在运算时会先转换类型
  alert(1 == '1');
  alert(1 == '2');
  alert(true == '1');
  alert(true == '2');
  alert(false == []);
  alert(undefined == null);

     2)、全等运算符(===):

//同样的例子可以证明,全等运算符在运算时不会转换类型
  alert(1 === '1');
  alert(true === '1');
  alert(false === []);
  alert(undefined === null);

除了判断相等和全等的运算符,还有判断不等(!=)和不全等(!==)的运算符,它们的行为基本相同。

【3】逻辑运算符

     1)、与运算符(&&):

//用作判断条件
  if(true && true) {
    alert('good!');
  }

  //用作变量赋值
  var a = true && 'good!';
  var b = false && 'good!';
  alert(a);
  alert(b);

     2)、或运算符(||):

//用作判断条件
  if(true || false) {
    alert('good!');
  }

  //用作变量赋值
  var a = true || 'good!';
  var b = false || 'good!';
  alert(a);
  alert(b);

     3)、非运算符(!):

//用作判断条件
  if(!false) {
    alert('good!');
  }

  //用作类型转换
  alert(!!1);

     4)、条件运算符(?:):

//条件判断结构
  if(true) {
    'good!';
  } else {
    'sorry!';
  }

  //条件运算结构
  true ? 'good!' : 'sorry!';

  //多分支条件判断结构
  if(true) {
    'good!';
  } else if(true) {
    'good!!';
  } else if(true) {
    'good!!!';
  } else {
    'sorry!'
  }

  //多分支条件运算结构
  true ? 'good!' : true ? 'good!!' : true ? 'good!!!' : 'sorry!' ;

  /*
    => 做为开发人员,应该养成良好的编码习惯,上边的代码如果写成这样,大家就会很容易明白。
    true ? 'good!'   :
    true ? 'good!!'  :
    true ? 'good!!!' :
           'sorry!'  ;
   */

逻辑运算符常用在条件判断和变量赋值,理解和学会使用它们,可以让代码在一定程度上更加简洁易懂。

【4】其它运算符

除了上边讲解的运算符外,JavaScript中还有许多运算符。它们的行为要么与之相似,要么用途非常简单,在这里列举了一些常用的,其他的可以多看看书。

原文地址:https://www.cnblogs.com/huige728/p/3085463.html