当前位置: 首页 > news >正文

JS代码优化技巧——持续更新

使前端代码更优雅的优化技巧,持续更新,转载自Hhua
.

多个条件的判断——数组的include方法

//Bad
if (x === 'iphoneX' || x === 'iphone11' || x === 'iphone12') {
	//code... 
}
//Good
if (['iphoneX', 'iphone11', 'iphone12'].includes(x)) {
	//code...
}

简单条件判断——三目运算符(可嵌套)

// Bad
let test= boolean;
if (x > 100) {
	test = true;
} else {
	test = false;
}
// Good
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;

判空——短路写法

// Bad
if (first !== null || first !== undefined || first !== '') {
	let second = first;
}
// Good 短路写法
let second = first|| '';

取整——双位操作符

// Bad
Math.floor(4.9) === 4  //true
// Good
~~4.9 === 4  //true

对象属性

const x,y = 5
// Bad
const obj = { x:x, y:y }
// Good
const obj = { x, y }

箭头函数——=>

//Bad
function sayHello(name) {
  console.log('Hello', name);
}
setTimeout(function() {
  console.log('Loaded')
}, 2000)
list.forEach(function(item) {
  console.log(item)
})
// Good
const sayHello = name => console.log('Hello', name)
setTimeout(() => console.log('Loaded'), 2000)
list.forEach(item => console.log(item))

隐式返回值

//Bad
function calcCircumference(diameter) {
  return Math.PI * diameter
}
// Good
const calcCircumference = diameter => (
  Math.PI * diameter
)

解构赋值

const form = { a:1, b:2, c:3 }
//Bad
const a = form.a
const b = form.b
const c = form.c
// Good
const { a, b, c } = form

展开运算符——…

const odd = [ 1, 3, 5 ]
const arr = [ 1, 2, 3, 4 ]
// Bad
const nums = [ 2, 4, 6 ].concat(odd)
const arr2 = arr.slice( )
// Good
const nums = [2 ,4 , 6, ...odd]
const arr2 = [...arr]

数组常见处理

const arr = [1,2,3]
//every 每一项都成立,才会返回true
console.log( arr.every(it => it>0 ) ) //true

//some 有一项都成了,就会返回true
console.log( arr.some(it => it>2 ) ) //true

//filter 过滤器
console.log( arr.filter(it => it===2 ) ) //[2]

//map 返回一个新数组
console.log( arr.map(it => it==={id:it} ) ) //[ {id:1},{id:2},{id:3} ]

//forEach 没有返回值
console.log( arr.forEach(it => it===console.log(it)) ) //undefined

//find 查找对应值 找到就立马返回符合要求的新数组
console.log( arr.find(it => it===it>2) ) //3

//findIndex 查找对应值 找到就立马返回符合要求新数组的下标
console.log( arr.findIndex(it => it===it>2) ) //2

//reduce 求和或者合并数组
console.log( arr.reduce((prev,cur) => prev+cur) ) //6

//includes 求和或者合并数组
console.log( arr.includes(1) ) //true

//数组去重
const arr1 = [1,2,3,3]
const removeRepeat = (arr) => [...new Set(arr1)]//[1,2,3]

//数组求最大值
Math.max(...arr)//3
Math.min(...arr)//1

//对象解构 这种情况也可以使用Object.assign代替
let defaultParams={
    pageSize:1,
    sort:1
}
//goods1
let reqParams={
    ...defaultParams,
    sort:2
}
//goods2
Object.assign( defaultParams, {sort:2} )

对象常用处理

const data = { test1: 'abc', test2: 'cde' }
const arr1 = Object.entries(data)
const arr2 = Object.values(data)
const arr3 = Object.keys(data)
/** arr1 Output:
[ 
    [ 'test1', 'abc' ],
    [ 'test2', 'cde' ],
]
**/
/** arr2 Output:
	['abc', 'cde']
**/
/** arr3 Output:
	['test1', 'test2']
**/

短函数调用

const test1 =() => {
  console.log('test1');
}
const test2 =() => {
  console.log('test2');
}
const test3 = 1;
if (test3 == 1) {
  test1()
} else {
  test2()
}
// Good
test3 === 1? test1():test2()

对象替换switch或复杂if…else

// Bad
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// Good
const data = {
  1: test1,
  2: test2,
  3: test
}
data[anything] && data[anything]()

// Bad
if (type === 'test1') {
  test1();
}
else if (type === 'test2') {
  test2();
}
else if (type === 'test3') {
  test3();
}
else if (type === 'test4') {
  test4();
} else {
  throw new Error('Invalid value ' + type);
}
// Good
const types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
const func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

重复一个字符串——repeat

//Bad 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test,'; 
} 
console.log(str);// test,test,test,test,test,

//good 
console.log('test,'.repeat(5))

幂的简写——**

//Bad 
Math.pow(2,3)// 8

//good 
2**3 // 8

数字分隔符——_

//old syntax
let number = 98234567
//new syntax
let number = 98_234_567

相关文章:

  • 文字居于div底部的方式
  • Element——el-table设置单元格间距
  • Vue——插槽语法
  • Element——给el-table表头添加*
  • Element——tooltip无效和自定义内容
  • Vue——provide/inject的使用
  • windows注册表自定义添加右键菜单
  • 请求正常执行但是js语法报错Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘code‘)
  • 使用图片做背景并设置充满固定屏幕
  • Vue——组件间数据访问方式与通信方式的一点总结思考
  • git-错误合并或错误删除文件并推送如何回退
  • 面试——常用的设计模式
  • VUE全局使用element-ui组件
  • express创建项目
  • React脚手架搭建及react项目新建
  • 2019.2.20 c++ 知识梳理
  • django开发-定时任务的使用
  • ECMAScript6(0):ES6简明参考手册
  • JavaScript设计模式系列一:工厂模式
  • MobX
  • React Native移动开发实战-3-实现页面间的数据传递
  • Ruby 2.x 源代码分析:扩展 概述
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • vue.js框架原理浅析
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 动态魔术使用DBMS_SQL
  • 飞驰在Mesos的涡轮引擎上
  • 聊聊springcloud的EurekaClientAutoConfiguration
  • 前端学习笔记之原型——一张图说明`prototype`和`__proto__`的区别
  • 通信类
  • 想写好前端,先练好内功
  • 用 Swift 编写面向协议的视图
  • 怎样选择前端框架
  • 找一份好的前端工作,起点很重要
  • ​Linux·i2c驱动架构​
  • ​总结MySQL 的一些知识点:MySQL 选择数据库​
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (C++20) consteval立即函数
  • (ZT)北大教授朱青生给学生的一封信:大学,更是一个科学的保证
  • (定时器/计数器)中断系统(详解与使用)
  • (附源码)node.js知识分享网站 毕业设计 202038
  • (附源码)springboot炼糖厂地磅全自动控制系统 毕业设计 341357
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (六)激光线扫描-三维重建
  • (学习日记)2024.04.10:UCOSIII第三十八节:事件实验
  • (一)【Jmeter】JDK及Jmeter的安装部署及简单配置
  • (原)本想说脏话,奈何已放下
  • (转)jQuery 基础
  • (转)ORM
  • (转载)利用webkit抓取动态网页和链接
  • .net mvc actionresult 返回字符串_.NET架构师知识普及
  • .net 流——流的类型体系简单介绍
  • .net使用excel的cells对象没有value方法——学习.net的Excel工作表问题
  • /var/lib/dpkg/lock 锁定问题