链判断运算符:?.
在api对接的时候,会出现一种情况后台某个字段某返回给你,然后你不得不做非空判断。
1 2 3 4 5 6
| ajax({ url: 'xxx' success(res) { let children = res.data.children } })
|
正常加判断的方法
1
| let children = res && res.data && res.data && res.data.children
|
是不是又丑又长,看看es6的写法
1
| let children = res?.data?.children
|
短了一大截,代码优雅多了
解构赋值
在React
的render
需要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 }
|
这种写法是不是有点麻烦,换成结构赋值的形式
1 2 3 4
| render() { const { name, city, phone } = this.state }
|
添加默认值
1 2 3 4
| render() { const { name, city, phone, sex = 'gg' } = this.state }
|
拓展运算符:…
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')
|
是不是对比正则更加直观