在 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
除了刷题之外的事 刷题是练习解决问题的能力的一种方法,而这里的「问题」主要是指演算法问题。但在实务...
Hashicorp Nomad: Docker driver image behavior 在Has...
在上一篇我们已经知道MVC路由和静态资源导入的方式 因此起手式 从新增专案.net core空专案到...
杂凑表,我需要那个酷东西 在线性资料结构中,若要找一个资料,花费的时间复杂度为O(n),或是可以选择...
一、前言 经营部落格,会是一个长期的网路事业,在初期有许多部分我认为就应该思考好,在整个经营路上才...