数算运算符

+ | - | * | / | % | ++ | -- console.log(5 / 2); 2.5

   取整 console.log('%d', 5 / 2); // "2"

  var num = parseInt(5 / 2); // 2

  console.log(num);

  取模(求余)

  console.log(5 % 2);  // 1

  任何一个自然数对 n 取余, 结果为 [0, n-1]

  自增|自减 ++|--

  ++就是自增1, --就是自减1

  var num = 10

  console.log(num++);  // 10

  console.log(++num);  // 12

  console.log(num);  // 12

  ++在变量后(num++), 先将变量的值拿去使用,再自身自增1

  ++再变量前(++num), 先将变量自身自增1, 再将结果拿去使用

  总结: 不管++在前在后,运算结束后,变量自身值一定自增1

  res = ++num  <==>  num++; res = num

  res = num++  <==>  res = num; ++num

  赋值运算符

  = | += | -= | *= | /= | %= var x = 10;

  将10的值赋值给变量x y = x;

  将变量x的值传递给变量y console.log(y); // 10

  x += 10;  // x = x + 10, 运算方式由右至左, 将x+10的结果重新复制给x

  console.log(y);  // 10, y的值虽然来源于x, 但y值只由自身控制

  x /= 10  == x = x / 10

比较运算符, 结果为Boolean类型

== | ===

console.log("5" == 5); // true, 只做值比较

console.log("5" === 5); // false, 比较值及类型

// != | !==

console.log("5" != 5);  // false, 只做值比较

console.log("5" !== 5);  // true, 比较值及类型

逻辑运算符, 运算结果通常为Boolean(可以不是)

或 | 与 | 非 <==> || | && | !

&&(与)

var a = 10;

var b = 20;

var c = "20";

var res = a < b && b == c;  // true

console.log(res)

总结&&: 全真为真, 有假则假

总结||: 全假则假, 有真则真

总结!: 真则假, 假则真

逻辑运算符的结果本质上为表达式值

表达式: 由数字,变量,运算符组成的合法式子

res = a < b && c;

console.log(res);

res = (a = 1 || b == c);

console.log(res);

针对 && | ||

疑问: 逻辑运算符结果可能为逻辑运算符之前表达式的值,也可能是之后表达式的值

当逻辑运算符出现 短路现象 , 就是之前表达式的值, 否则(正常情形下), 就是之后表达式的值

&&, 前一个表达式为假时, 整个式子的结果已经确定为假, 后表达式不会被执行, 就是被短路了

var num = 10;

res = false && num++;

console.log(res, num);  // null, 10

res = null && ++num;

console.log(res, num);  // null, 10

||, 前一个表达式为真时, 整个式子的结果已经确定为真, 后表达式不会被执行, 就是被短路了

res = -10 || ++num;

console.log(res, num);  // -10, 10

特殊小技巧 => 类似于if分支来使用

if a > b:

    print(a)

var a = 100;

a > b && console.log("大值a:", a);

三目运算符

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

var a = 10, b = 20; var res = a < b ? a : b; 取小值

console.log(res); res = a < b ? b : a; // 取大值

console.log(res);

类似于if...esle...

a < b ? console.log("表达式结果为true") : console.log("表达式结果为false")

let abc = 10;

let abc = 20; // 在es6语法下,有变量的重复定义规则, 不允许在同一作用域下,出现变量的重复定义 { let abc = 20; // 可以编译运行通过 }

// ES6新增

let [a1, b1, c1] = [1, 2, 3];

// a1=1,b2=2,c3=3

let [a2, ...b2] = [1, 2, 3];

// a2=1,b2=[2,3]

let {key: a3} = {key: 10};

// a3=10

let [a4, b4, c4] = 'xyz';

// a4='x',b4='y',c4='z'

console.log("end")

原文地址:https://www.cnblogs.com/zhouhai007/p/10139976.html