es6的超好用的写法

链判断运算符:?.

在api对接的时候,会出现一种情况后台某个字段某返回给你,然后你不得不做非空判断。

1
2
3
4
5
6
ajax({
url: 'xxx'
success(res) {
let children = res.data.children // Uncaught TypeError: Cannot read property 'data' of undefined
}
})

正常加判断的方法
1
let children = res && res.data && res.data && res.data.children

是不是又丑又长,看看es6的写法
1
let children = res?.data?.children

短了一大截,代码优雅多了


解构赋值

Reactrender需要state里面的几个参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
this.state = {
name: 'oyt',
sex: '1',
city: '广州',
phone: '13312345678'
// ...
}

render() {
const _state = this.state
const name = _state.name
const city = _state.city
const phone = _state.phone
// do something
}

这种写法是不是有点麻烦,换成结构赋值的形式

1
2
3
4
render() {
const { name, city, phone } = this.state
// do something
}

添加默认值

1
2
3
4
render() {
const { name, city, phone, sex = 'gg' } = this.state
// do something
}

拓展运算符:…

1
2
3
4
5
6
7
8
9
10
11
// 数组
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = a.concat(b) // 正常合并数组
let d = [...a, ...b] // 拓展运算符

// 对象
let e = { a, b }
let f = { c, d }
let g = Object.assign({}, e, f) // 正常合并对象
let h = { ...e, ...f } // 拓展运算符

字符串includes方法

正常我们判断字符串中是否存在某个字段是这样的。

1
2
3
4
5
6
7
8
const str = 'Hello World'

const flag = haveStr(str, 'll')

function haveStr(target, val) {
if(!val) return
return target.indexOf(val) !== -1
}

includes写法
1
2
const str = 'Hello World'
const flag = str.includes('ll')

拓展另一种骚写法
1
2
3
4
5
6
7
8
const str = 'Hello World'

const flag = haveStr(str, 'll')

function haveStr(target, val) {
if(!val) return
return !!~target.indexOf(val)
}


字符串replaceAll方法

正常替换字符串中的匹配字符串

1
2
3
4
let str = 'aabbccdd'

str.replace('a', 'k') // 这种只能替换首个匹配的,所以匹配所有只能改成正则
str.replace(/a/g, 'k')

replaceAll写法
1
2
3
let str = 'aabbccdd'

str.replaceAll('a', 'k')

是不是对比正则更加直观


es6的超好用的写法
作者
墨陌默
发布于
2020年11月24日
许可协议