JS运算符

81 阅读2分钟

算术运算符

number运算

  • 加减乘除
  • 余数x%7 特殊:
console.log(-1 % 7) //-1
  • 指数x**3
  • 自增自减x++/++x/x--/--x
//a在前,值为前;a在后,值为后
  • 求值运算符+x,+号只是说求一下这个数的值
var a = -8
console.log(+a) //-8
  • 负数运算符-x

string运算

  • 连接运算'123'+'456',字符串只支持+号运算

注意

console.log(1+'2') // 字符串"12",过程是先把1变成字符串,然后'1'+'2'
console.log('2'-1) // 数字1,由于字符串不支持减号,先把字符串变成数字2,然后减去1

比较运算符

  • >
  • <
  • >=
  • <=
  • == (模糊相等)
console.log( 0 == []) //true
console.log( 0 == '0') //true
console.log( 0 == '\t') //true
console.log( [] == '0') //false
console.log( '0' == '\t') // false
console.log( [] == '\t') //false
//永远不要使用 ==,用===代替,==的问题在于,它总是自动类型转换
// 0 NaN null undefined '' 值为false
var a = []
if(a) {console.log('hi')} //hi
var a = []
if(a == true) {console.log('hi')} //undefined
  • != (不模糊相等)
  • === (全等,基本类型看值是否相等,对象看地址是否相等,[] !== [],{} !== {})
console.log(0 === []) //false,类型不相等,直接不相等
console.log([] === []) //false,#101和#108
console.log({} === {}) //false
  • NaN !== NaN
  • !== (不全等)

布尔运算符

或且非

  • ||
  • &&
  • !

短路逻辑

console && console.log && console.log('hi'),以防console不存在报错

image.png

a = a || 100,a的保底值

function add(n=0) {
    return n+1
}    
add(null) //1
add(undefined) //1
add('') //"1"

二进制位运算符

或、与、否

  • |两个位都为0,则结果为0,否则为1
  • & 两个位都为1,则结果为1
  • ~

异或

  • ^
  • 两个位相同,则结果为0,否则为1

左移右移

  • <<和>>

头部补零的右移运算符

  • >>>

使用与运算符判断奇偶

&1 = 0 //偶数,偶数二进制最后一位是0
&1 = 1 //奇数

使用~,>>,<<,>>>,|来取整

// 位运算有一个特点:位运算不支持小数,所以它在算的过程中把小数部分抹去了,所以以下式子都是变为整数
console.log(~~6.83) //6
console.log(6.83 >> 0) //6
console.log(6.83 << 0) //6
console.log(6.83 | 0) //6
console.log(6.83 >>> 0) //6

使用^来交换a b的值

var a = 5
var b = 8
a ^= b
b ^= a
a ^= b
console.log(a) //8
console.log(b) //5
//新版语法
var a = 1
var b = 2
[a,b] = [b,a]
console.log(a,b) //2,1

其他运算符

点运算符

//对象.属性名 = 属性值
//作用:读取对象的属性值
//JS有特殊逻辑,点前面不是对象,就把它封装成对象
//例如: 
var a = 1
a.toString() //这个地方js会自动的把a变为对象
//number会变成Number对象,string会变成String对象,bool会变成Boolean对象
<a href="javascript:;">baidu</a>

逗号运算符

var a = (1,2)

let f = x=>(console.log('hi'),x+1)
f(1) //hi 2

运算符优先级注意点

//a = b = c = d = 2
//等价于a = (b = (c = (d = 2))),(d=2) 先把2赋值给d,得到这个表达式(d=2)的值为2,然后把这个2的值赋值给c,(c=2)的值还是2,把这个值赋值给b,(b=2)的值还是2,把这个值赋值给a,这就是赋值号从右往左这个规律

资料来源:饥人谷