JavaScript演算子
例
変数に値を割り当て、それらを一緒に追加します。
let x = 5; // assign the value 5 to
x
let y = 2; // assign the value
2 to y
let z = x + y; // assign the value 7 to z (5 + 2)
代入演算子( )は=
、変数に値を代入します。
割り当て
let x = 10;
加算演算子(+
)は数値を加算します。
追加する
let x = 5;
let y = 2;
let z = x + y;
乗算演算子(*
)は数値を乗算します。
掛け算
let x = 5;
let y = 2;
let z = x * y;
JavaScript算術演算子
算術演算子は、数値の算術を実行するために使用されます。
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
** | Exponentiation (ES2016) |
/ | Division |
% | Modulus (Division Remainder) |
++ | Increment |
-- | Decrement |
算術演算子については、 JS算術の章で詳しく説明しています。
JavaScript代入演算子
代入演算子は、JavaScript変数に値を代入します。
Operator | Example | Same As |
---|---|---|
= | x = y | x = y |
+= | x += y | x = x + y |
-= | x -= y | x = x - y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
%= | x %= y | x = x % y |
**= | x **= y | x = x ** y |
加算代入演算子( )は+=
、変数に値を加算します。
割り当て
let x = 10;
x += 5;
代入演算子については、 JS代入の章で詳しく説明しています。
JavaScript文字列演算子
+
演算子を使用して、文字列を追加(連結)することもできます。
例
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
text3の結果は次のようになります。
John Doe
代入演算子を使用して、+=
文字列を追加(連結)することもできます。
例
let text1 = "What a very ";
text1 += "nice day";
text1の結果は次のようになります。
What a very nice day
文字列で使用する場合、+演算子は連結演算子と呼ばれます。
文字列と数値の追加
2つの数値を加算すると合計が返されますが、数値と文字列を加算すると文字列が返されます。
例
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
x、y、およびzの結果は次のようになります。
10
55
Hello5
数字と文字列を追加すると、結果は文字列になります!
JavaScript比較演算子
Operator | Description |
---|---|
== | equal to |
=== | equal value and equal type |
!= | not equal |
!== | not equal value or not equal type |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
? | ternary operator |
比較演算子については、 JSの比較の章で詳しく説明しています。
JavaScript論理演算子
Operator | Description |
---|---|
&& | logical and |
|| | logical or |
! | logical not |
論理演算子については、JSの比較の章で詳しく説明しています。
JavaScript型演算子
Operator | Description |
---|---|
typeof | Returns the type of a variable |
instanceof | Returns true if an object is an instance of an object type |
型演算子については、 JS型変換の章で詳しく説明しています。
JavaScriptビット演算子
ビット演算子は32ビットの数値で機能します。
演算の数値オペランドは、32ビットの数値に変換されます。結果はJavaScript番号に変換されます。Operator | Description | Example | Same as | Result | Decimal |
---|---|---|---|---|---|
& | AND | 5 & 1 | 0101 & 0001 | 0001 | 1 |
| | OR | 5 | 1 | 0101 | 0001 | 0101 | 5 |
~ | NOT | ~ 5 | ~0101 | 1010 | 10 |
^ | XOR | 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 |
<< | left shift | 5 << 1 | 0101 << 1 | 1010 | 10 |
>> | right shift | 5 >> 1 | 0101 >> 1 | 0010 | 2 |
>>> | unsigned right shift | 5 >>> 1 | 0101 >>> 1 | 0010 | 2 |
上記の例では、4ビットの符号なしの例を使用しています。ただし、JavaScriptは32ビットの符号付き数値を使用します。
このため、JavaScriptでは、〜5は10を返しません。-6を返します。
〜00000000000000000000000000000101は11111111111111111111111111111010を返します
ビット演算子については、JSビット単位の章で詳しく説明されています。