js的运算符
赋值运算符(Assignment operators)
赋值运算符是一个 “=”。表示将“=”后面的内容赋值给左边的内容。
比较运算符(Comparison operators)
var a = 1, b = 2, c = '1';
if (a = c) { // 将c的值赋值给a,再判断a转换成布尔后的值是true还是false
console.log(true); // true
} else {
console.log(false);
}
if ('false') { // 此外的false是字符串类型,且为非空字符串,因此转换的布尔值为true
console.log(true);
}
算数运算符(Arithmetic operators)
加减乘除取余
var a = 2, e = 5;
console.log(a + e); // 7
console.log(a - e); // -3
console.log(a * e); // 10
console.log(e / a); // 2.5
console.log(e % a); // 1 取余数
逻辑运算符(Logical operators)
|| 或者、&&并且、!非
// || 或,先看左边,若左边为true,结果等于左边;或左边为false,结果等于右边
var a = 1, b = 2, c = 0, d = false;
console.log(a || b); // 1
console.log(a || c); // 1
console.log(c || a); // 1
console.log(c || d); // false
// && 且,先看左边,左边为true,结果等于右边,左边为false,结果等于左边
console.log(a && b); // 2
console.log(a && c); // 0
console.log(c && a); // 0
console.log(c && d); // 0
// ! 非,取反
console.log(!a); // false
console.log(!c); // true
字符串运算符(String operators)
JS中用 加号(+) 连接两个字符串。
如果使用+的是两个数字,则表示加法运算;如果使用+的有一方是字符串,则表示字符串连接。
console.log(2 + 3); // 5
console.log(2 + 'hello'); // 2hello
console.log('hello' + 'world'); // helloworld
条件(三元)运算符(Conditional operator)
元,表示参与运算的参数个数。三元意思就是参与运算的有三个值。
var b = 2, c = 3, x = 4, y = 5;
var a = (b > c) ? x : y;
console.log(a); // 5
上述代码整体意思是给a赋值,值可能是x,也可能是y。关键取决于b是否大于c。如果b>c,则将x赋值给a;如果b不大于c,则将y赋值给a。
转载必须注明出处:https://www.zhiqiexing.com/133.html