超级实用的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'}
仍会补充……
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2020-07-15 常用 Git 命令清单
2020-07-15 css 文本超出隐藏并且显示省略号