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