本文已参与「新人创作礼」活动,一起开启掘金创作之路
1. 给变量设置默认值
let toto
console.log(toto) //undefined
toto = toto ?? 'default value'
console.log(toto) //default value
toto = toto ?? 'new value'
console.log(toto) //default value
2. 可选项
const toto = { a: { b: { c: 5 } } }
if (!!toto.a && !!toto.a.b && !!toto.a.b.c) { ... } // toto.a.b.c exist
简写:
if (!!toto.a?.b?.c) { ... } // toto.a.b.c exist
// 如果键不存在,返回 `undefined`。
const test = toto.a?.b?.c?.d // undefined
3.模板字符串
例:
- 普通写法:
const toto = 'toto'
const message = 'hello from ' + toto + '!' // hello from toto!
- ES6模板写法
const toto = 'toto'
const message = `hello from ${toto}!` // hello from toto!
4.对象和数组结构
// 对象
const student = {
name: 'Sam',
age: 22,
sex: '男'
}
// 数组
// const student = ['Sam', 22, '男'];
// ES6
const { name, age, sex } = student;
console.log(name + ' --- ' + age + ' --- ' + sex);
5.IF条件简写
- 如果判断值满足多个条件,我们可能会这么写
if (value === 'a' || value === 'b' || value === 'c')
{ ... }
- 像这样如果有多个条件,if 条件就会很我,可读性降低,我们可以这样简化:
if (['a', 'b', 'c'].includes(value)) { ... }
2.!(NOT)运算符可以使用两次!!,这样可以将任何变量转换为布尔值(像布尔函数),当你需要在处理它之前检查某个值时非常方便。
const toto = null
!!toto // false
Boolean(toto) // false
if (!!toto) { } // toto is not null or undefined
3.如果if中返回值时, 就不要在写 else
if (...) {
return 'toto'
}
return 'tutu'
- 当条件为 true 时,执行某些操作,我们可能会这样写:
之前写法:
if(condition){
toto()
}
简写:
condition && toto()