JS操作符

只记录自己比较容易忘记的概念和内容,方便以后查阅。原文请参考:http://javascript.info/operators

二元运算符(+/-*)

对于 + 运算符,只要有一个操作数是字符串,将会另外一个也转为字符串,如:
The rule is simple: if either operand is a string, the other one is converted into a string as well

let s = 'my'+'string';
alert(s); // mystring
alert('1'+2); //'12'
alert(2+'1'); //'21'
alert(2+2+'1'); //'41' and not '221'

其他运算符(/-*)只会对数字进行运算,所以它们会先将非数字的操作数转为数字,然后再运算,如:

alert(2-'1'); //1
alert('2'-'1'); //1
alert('3'-1); //2
alert('5'/2); //2.5
alert('3'*3); //9

一元运算符(+)

对于一元运算符 + ,当操作数为数字时,不会操作数字。当不是数字时,将会转为数字,相当于Number(…),如:
The unary plus or, in other words, the plus operator + applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.

let x = 1;
alert(+1); // 1
let y = -2;
alert(+y); // -2
alert(+true); // 1
alert(+''); // 0
alert(+'3'++'4'); // Uncaught SyntaxError: Invalid left-hand side expression in postfix operation
alert(+'3'+ +'4'); // 7 一元运算符优先级高于二元运算符

赋值操作符(=)

赋值运算优先级低于二元运算。赋值运算可以链式执行,且会返回最左端变量的值,如:
The call x = value writes the value into x and then returns it.

let a, b, c, d;
a = b = c = 2+2;
alert(a); // 4
alert(b); // 4
alert(c); // 4
alert(d = 2+5); //7 先将2+5的值赋值给d,然后返回d的值传给alert

求幂运算符(**)

求幂运算符是ES6新增的特性,a**b表示将a进行b次相乘,返回相乘后的结果。如:

alert(2**3); // 8 2的3次方
alert(4**5); // 1024 4的5次方
alert(8**(1/3)); // 2 8的1/3次方

逗号运算符( , )

逗号运算符最常见在被压缩后的js代码中。 逗号运算会从左到右计算每个表达式的值,最后返回最右边一个的值,如:

let a = (1+2, 3+4); //将a赋值给一个逗号表达式
alert(a); // 7 a取最右边的表达式的值

逗号表达式的优先级很低,比赋值运算还要低,如:

let a = 1+2, 3+4;
alert(a); // 3 先运算1+2=3,再将3赋值给a,忽略3+4,再将a的值传给alert
let s = a=1+2,3+4;
alert(s); // 7 传给alert的值是逗号表达式(3,7)的返回值,所以相当于alert(7)

 

 

单词

operandn. [计] 操作数;[计] 运算对象
operator n. 操作符
unary n. 一元操作符
binary n. 二元操作符
terminology n. 术语,术语学;用辞
operator precedence 英 /ˈpresɪdəns/ n. 运算符优先级

 

句子

  1. Let’s grasp some common terminology. 让我们掌握一些常用术语。
posted @ 2019-10-18 02:27  ywxgod  阅读(317)  评论(0编辑  收藏  举报