Operators

Terms: “unary”, “binary”, “operand”

5 * 2
// 5 = right operand
// 2 = left operand 
// operand sometimes call arguments

// An operator is unary

let x = 1;
x = -x;
alert( x ); // -1, unary negation was applied

// An operator is binary

let x = 1, y = 3;
alert( y - x ); // 2, binary minus subtracts values

String concatenation, binary +

+ 若有一邊的值是字串會轉換成字串相加。

alert(2 + 2 + '1' ); // "41" and not "221"

Numeric conversion, unary +

unary + 把值轉換成數字

// Converts non-numbers does the same thing as Number(...)
alert( +true ); // 1
alert( +"" );   // 0

如果從 HTML 得到值通常是字串,可以用 + 轉換成數字。

let apples = "2";
let oranges = "3";

// both values converted to numbers before the binary plus
// unary + precedance > binary precedance
alert( +apples + +oranges ); // 5

// the longer variant
// alert( Number(apples) + Number(oranges) ); // 5

Operator precedence

再數學裡有運算規則,像是先加減後乘除,程式裡也有運算規則 precedence table

Assignment

= 也是運算符號,通常返回一個值,並由右到左執行。

let a, b, c;

a = b = c = 2 + 2;

alert( a ); // 4
alert( b ); // 4
alert( c ); // 4

Remainder %

計算餘數

alert( 5 % 2 ); // 1 is a remainder of 5 divided by 2
alert( 8 % 3 ); // 2 is a remainder of 8 divided by 3
alert( 6 % 3 ); // 0 is a remainder of 6 divided by 3

Exponentiation **

計算次方

alert( 2 ** 2 ); // 4  (2 * 2)
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root, that's maths)

Increment / decrement

let counter = 2;
counter++;      // works the same as counter = counter + 1, but is shorter
alert( counter ); // 3

let counter = 2;
counter--;      // works the same as counter = counter - 1, but is shorter
alert( counter ); // 1

alert( 5++ ); // error only applied to variables

在過程中使用前綴或後綴沒有差別,但結果包含前綴跟後綴是有差別的。

let counter = 0;
counter++;
++counter;
alert( counter ); // 2, the lines above did the same

let counter = 0;
alert( ++counter ); // 1 prefix

let counter = 0;
alert( counter++ ); // 0 postfix

Bitwise operators

  • AND ( & )

  • OR ( | )

  • XOR ( ^ )

  • NOT ( ~ )

  • LEFT SHIFT ( << )

  • RIGHT SHIFT ( >> )

  • ZERO-FILL RIGHT SHIFT ( >>> )

Modify-in-place

想要對變數做運算後,儲存新的值在同一變數可以使用縮寫。

let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)

alert( n ); // 14

Comma

最奇怪的運算符號,可以運算多個運算式,用,分開,但只有最後一個值會被返回。

let a = (1 + 2, 3 + 4);

alert( a ); // 7 (the result of 3 + 4)

// three operations in one line
for (a = 1, b = 3, c = a * b; a < 10; a++) {
 ...
}

Last updated