js开发中代码的优化
** 希望在新的2021年大家一起学习,分享**
1、null、undefined、''检查
在创建新变量赋予一个存在的变量值的时候,并不希望赋予 null 或 undefined,我们可以采用一下简洁的赋值方式。
if(test !== null || test !== undefined || test !== ''){
let a1 = test;
}
// 优化
let a1 = test || ''
2、null 值检查并赋予默认值
let test = null;
let a1 = test || '测试';
3、undefined 值检查并赋予默认值
let test = undefined;
let a1 = test || '测试2';
4、声明变量
当我们想要声明多个共同类型或者相同值的变量时,我们可以采用一下简写的方式。
let test1;
let test2 = 0;
// 优化
let test1, test2 = 0;
5、if 多条件判断
当我们进行多个条件判断时,我们可以采用数组 includes 的方式来实现简写。
if(test === '1' || test === '2' || test === '3' || test === '4'){
// 逻辑
}
// 优化后
if(['1','2','3','4'].includes(test)){
// 逻辑处理
}
6、if...else 的简写
当存在一层或两层 if...else嵌套时,我们可以使用三元运算符来简写
let test = null;
if(a > 10) {
test = true;
} else {
test = false;
}
// 优化后
let test = a > 10 ? true : false;
// 或者
let test = a > 10;
7、字符串转数字
let a1 = parseInt('100');
let a2 = parseFloat('10.1');
// 简写
let a1 = +'100';
let a2 = +'10.1';
8、多变量赋值
当我们想给多个变量赋不同的值的时候,我们可以采用一下简洁的速记方案。
let a = 1;
let b = 2;
let c = 3;
// 优化
let [a, b, c] = [1, 2, 3];
9、算术运算简写优化
当我们在开发中经常用到算数运算符时,我们可以使用一下方式进行优化和简写。
let a = 1;
a = a + 1;
a = a - 1;
a = a * 2;
// 优化
a++;
a--;
a *= 2;
10、有效值判断
我们经常会在开发中用到的
if (test1 === true)
if (test1 !== "")
if (test1 !== null)
// 优化
if (test1)
11、多个比较 return
在 return 的语句中使用比较,可以将其进行缩写。
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return foo('test');
}
}
// 优化
function checkReturn() {
return test || foo('test');
}
12、箭头函数
function add() {
return a + b;
}
// 优化
const add = (a, b) => a + b;
13,短函数调用
function fn1(){
console.log('fn1');
}
function fn2(){
console.log('fn1');
}
if(type === 1){
fn1();
}else{
fn2();
}
// 优化
(type === 1 ? fn1 : fn2)();
14,数组合并与克隆
合并
const data1 = [1, 2, 3];
const data2 = [4 ,5 , 6].concat(data1);
// 优化
const data2 = [4 ,5 , 6, ...data1];
克隆:
const data1 = [1, 2, 3];
const data2 = test1.slice()
// 优化
const data1 = [1, 2, 3];
const data2 = [...data1];
15,字符串模版
const test = 'hello ' + text1 + '.'
// 优化
const test = `hello ${text}.`
16,数据解构
const a1 = this.data.a1;
const a2 = this.data.a2;
const a3 = this.data.a3;
// 优化
const { a1, a2, a3 } = this.data;
17,对象属性简写
let key1 = '1';
let key2 = 'b';
let obj = {key1: key1, key2: key2};
// 简写
let obj = {
key1,
key2
};