ES6语法糖,超甜!

ES6 语法糖

1. ...

... 表示取出可遍历数组中的内容。

const arr = new Array()
const numbers = [1,2,3,4,5]
arr.push(...numbers)// arr内容:1 2 3 4 5,即将numbers的内容挨个取出然后push到arr中

据说,ES7中可以拿来遍历对象

2. ??

?? 是空值合并操作符,按照第一个取值,如果第一个是空的,就取第二个。

const str
const content = str ?? "str 内容为空" // 相当于 const content = str? str : "str 内容为空"

注意:只对 null 和 undefined 敏感

3. ?.

?.是可选链操作符,功能等同于.但是不会在引用为null或undefined时报错。当需要做判定时很有用,少写很啰嗦的代码,还很自然
为了保证兼容以前的代码,允许foo?.3:0被解析成foo ? .3 : 0,因此规定如果?.后面紧跟一个十进制数字,那么?.不再被看成是一个完整的运算符,而会按照三元运算符进行处理,也就是说,那个小数点会归属于后面的十进制数字,形成一个小数。

class Media{
    constructor(fileName, content, duration){
        this.fileName = fileName
        this.content = content
        this.duration = duration
    }
}

const media
const fileName = media.?fileName // 相当于 const fileName = media? media.fileName : undefined

a?.b
// 等同于
a == null ? undefined : a.b

a?.[x]
// 等同于
a == null ? undefined : a[x]

a?.b()
// 等同于
a == null ? undefined : a.b() // 若a中存在b,但是b不是方法,会报错

a?.()
// 等同于
a == null ? undefined : a() // 若a不是方法,会报错


2023年1月13日 14点34分

4. **

**表示指数运算符,多个连用时注意右结合

2 ** 2 // 4,2的平方

2 ** 3 ** 4 // 指的是 2 ** (3 ** 4)

5. ||

|| 只要属性的值为nullundefined或 空字符串 或 false0,默认值会生效。这个使用场景不是很多,现在已经被??替代(只要是null或者undefined

const a = b || c // 相当于 if(!b || b === '' || b === 0) a = c

参考

  1. https://www.cnblogs.com/zhigu/p/13962661.html
  2. https://blog.csdn.net/yc__coder/article/details/120431174
  3. https://es6.ruanyifeng.com/?search=链判断 (这个可以当参考书查)

To Be Continue!

posted @ 2023-01-05 17:41  echo_lovely  阅读(102)  评论(0编辑  收藏  举报