JavaScript 代码简写技巧
进入团队之后,在看前辈的代码式发现有许多js的编写技巧跟自己有所不同,第一时间感觉脑袋要转一下弯才能想过来。到了后面逐渐也被这种简写所影响,因此根据网上的文章以及自己的理解对js的代码简写做了一个总结。
常规篇
-
三目运算符替代if else
//原生语句 const x = 20 let name if (x > 10) { name = '匿寻' } else { name = '康康' } //简写版本 const name = x > 10 ? '匿寻' : '康康'
-
循环语句 for of 替代 for i
//原生语句 for (let i = 0; i < arr.length; i++) //简写版本 for (let item of arr) arr.forEach(res =>{})
-
模板字符串代替双引号(双引号在换行时必须使用+连接)
//原生语句 const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t' + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t' const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim`
-
用||进行变量赋值
//原生语句 let variable1,variable2 if (variable1 !== null || variable1 !== undefined || variable1 !== '') { variable2 = variable1; } else{ variable2 = "new" } //简写版本 const variable2 = variable1 || 'new';
ES6 简写大全
-
对象属性key和value相同
//原生语句 const obj = { x:x, y:y } //简写版本 const obj = { x, y }
-
箭头函数
//原生语句 function add (x, y){ return x+y; } //简写版本 let add = (x, y) =>{ x+y } tips: 1.如果只有一个参数,括号可以省略。 2.如果一个参数都没有必须有括号 3.函数体内如果只有一条return语句,可以省略return关键字 4.箭头函数的this时逐渐往上层冒泡查询的
-
解构赋值
//原生语句 const observable = require('mobx/observable') const action = require('mobx/action') const store = this.props.store const form = this.props.form const loading = this.props.loading //简写版本,loding:load 为重新命名 import { observable, action } from 'mobx' const { store, form, loading: load} = this.props
-
扩展操作符 ...
//原生语句 const odd = [1, 3, 5] const nums = [2 ,4 , 6].concat(odd) //简写版本 const odd = [1, 3, 5 ] const nums = [2 ,4 , 6, ...odd] //将扩展操作符和解构赋值结合使用 const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 } console.log(a) // 1 console.log(b) // 2 console.log(z) // { c: 3, d: 4 } tips: 1.扩展操作符不仅可以运用在数组上也能运用在对象上面 2.在数组操作上不仅能合并数组,还能复制,删减等