Intro

Web Dev Basic里和JS相关的最后一块内容是语法糖,简单来说,就是一些让编写体验更爽的语法规则

` Template Literals

这是一个用来在JS里更加方便地拼接字符串的语法糖

以往在需要拼接变量和字符串的时候,需要使用+号不断连接,而使用这个语法糖的话,只需要:

  • 将引号换为`
  • 在`包围的字符串里, 任何需要拼接的变量或者需要执行的函数,使用 ${}占位

举个例子来说,在以前我们拼接变量需要这么写

1
2
const dt = new Date();
console.log("Hi,"+name+". I am at"+ dt);

有了这个语法糖就能够写成

1
console.log(`Hi, ${name}. I am at ${dt}.`);

? Ternary Operator

这是一个用于替代if的语法糖,具体的写法是expr ? ifTrue : ifFalse

这种写法在react中比较常见,同时在其他语言中也经常出现

还是用例子来说明

1
2
3
4
5
6
7
const age = 17;
let msg;
if (age >= 18) {
msg = "You are old enough";
} else {
msg = "You are not old enough";
}

上面是最普通的条件分支的写法,有了这个语法糖,就能够写成一行

1
2
const age = 17;
const msg = age >= 18 ? "You are old enough" : "You are not old enough";

... Spread Operator

这是一个用现有数据来创建新数据的语法糖

具体使用方法是

1
2
const bands = ["Popipa", "Roselia", "RAS", "Morfonica"];
const newBands = [...bands, "MyGO"];

这里的newBands其实就是原来的bands的数据再加上一个新的MyGO

同样的,...也可以用在对象里

1
2
3
4
5
6
7
8
9
const defs = {
erf: "a plot of land",
people: "turbulent seas"
}

const newDef = {
...defs,
futz: "waste of time"
}

需要注意的是,这些都是shallow copy

? Optional Chaining

使用问号来判断不知道是否还存在的字段时非常有用

具体的使用案例可以和代码里一样

1
2
const mgmt = { cfg: { options: { src: { port: 3761 }}}}
const port = mgmt?.cfg?.options?.src?.port;

这样子的写法可以省去判断每一个对象是否存在,就不用再写if和判断条件了

?? Null Coalescing Operator

这个语法糖判断,如果左侧是null或者undefined,则使用右侧的值,比如

1
2
const IS_ENABLED = env.IS_ENABLED ?? true;
const USERNAME = document.getElementById("username").value ?? "";