在 JavaScript 裡 Operator(運算子)有很多種,這邊來介紹幾個常用的運算子,包括算術運算子、指派運算子、比較運算子、邏輯運算子...等,還有 2 個比較進階的用法 Nullish coalescing operator & Optional Chaining(不知道中文怎翻比較好抱歉 XD)![]()
算數運算子
除了 + 、 - 、 * 、 / 之外,還有 %、++ 、 -- 、** 等。
% 取餘數console.log(17 % 3); //2
console.log(15 % 2); //1
++、--++ 表示加 1,-- 表示減 1。let x = 0;
x++;
console.log(x); // 1
let x = 2;
x--;
console.log(x); // 1
** 次方console.log(7**4); // 為 7 的 4 次方
console.log(2**10); // 為 2 的 10 次方
指派運算子
= 將第二個運算元的值儲存在第一個運算元所指定的物件 (簡單指派)。+= 將第一個運算元的值加上第二個運算元的值;將結果儲存在第一個運算元所指定的物件,其他算術運算子方法亦同,Ex:-= 、 *= 、 /=。let x = 2;
x += 1;
console.log(x); // 3
比較運算子
==(等於)3 == "3",左邊的 3 是數字,右邊的 3 是字串,即使資料類型不一樣,但值一樣就是 true。===(嚴格等於)"3" === "3" 資料類型一樣,值也一樣,結果為 true。3 === "3" 值相同但資料類型不同,則結果為 false。!=(不等於)4 != "4",雖然資料類型不同,但值相同,結果就為 false。!==(嚴格不等於)4 !== "4",兩者資料類型不同,所以結果為 true。>、<、>=、<=邏輯運算子
Optional Chaining ?.
let lost = {owner:"Amy", wallet : { cash:10000 } };
// 確認錢包是否還在,假如錢包被偷走了肯定拿不回裡面的錢
console.log(lost.wallet && lost.wallet.cash); // 10000
// 改成 Optional Chaining 的寫法
console.log(lost.wallet ?. cash); // 10000
Nullish coalescing operator ??
當 ?? 左邊的東西是 null 或是 undefined 時,就把 ?? 右邊的值給它。
例如:a ?? b,如果 a 不是 null 或 undefined,結果就是 a,反之,如果 a 是 null 或 undefined,結果就是 b。
let yourGirlfriend;
console.log(yourGirlFriend); // undefined
console.log(yourGirlfriend ?? "yourhands"); // yourhands
上面的例子只宣告了 yourGirlfriend 這個變數,但沒有給她值(undefined),因為你沒有女朋友,所以這時候結果會是 ?? 右邊的值 yourhands![]()
是不是很簡單又好用呢~~~
參考資料:
MDN - Expressions and operators
Nullish coalescing operator