超级实用的ES6用法总结
1.取值问题:通过解构赋值来取值
const obj = { a: 1, b: 2, c: 3, d: 4, e: 5 } const { a, b, c, d, e } = obj // 结构对象不能为undefined或者null console.log(a, b, c, d, e) // 1 2 3 4 5
2.合并数据:通过扩展运算符进行数组合并去重,对象合并等
const a = [1, 2, 3] const b = [1, 4, 5, 6] const c = [...new Set([...a, ...b])] console.log(c) // [1, 2, 3, 4, 5, 6] const obj1 = { a: 1 } const obj2 = { b: 2 } const obj = { ...obj1, ...obj2 } console.log(obj) // {a: 1, b: 2}
3.拼接字符串:使用模板字符串进行拼接
const name = 'tian' const age = 18 const info = `my name is ${name},age is ${age}` console.log(info) // my name is tian,age is 18
4.if条件判断:使用ES6中数组实例方法includes
const condition = [1, 2, 3, 4] console.log(condition.includes(1)) // true console.log(condition.includes(5)) // false
5.列表搜索:常用filter,ES6中find()可性能优化,即搜索到符合条件的项就不会再继续遍历
const arr = [1, 2, 3, 4, 5, 7, 8] const result = arr.find(item => item === 3) console.log(result) // 3
6.获取对象属性值:可选链操作符
const obj = { name: 'name', age: '111', title: 'title' }
const name = obj?.name
7.输入框非空的判断:空值合并运算符
if ((input.value ?? '') !== '') {}
8.添加动态变化属性名的属性:
const obj = {} const index = 1 obj[`text${index}`] = 'text' console.log(obj) // {text1: 'text'}
仍会补充……