不可错过的JS代码优化技巧(持续更新)

2023-03-07,,

1. 带有多个条件的 if 语句

把多个值放在一个数组中,然后调用数组的 includes 方法。

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}

2. if 判断值是否存在

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //检查空字符串、null或者undefined
if (test1)

3. 用于多个条件判断的 && 操作符

//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();

4.延展操作符简化

//longhand
// 使用concat连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
// 连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

5.将字符串转成数字

//Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//Shorthand
let test1 = +'123';
let test2 = +'12.3';

6. 解构赋值

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;

7.条件查找简化

// Longhand
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);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

8.indexOf 的按位操作简化

在查找数组的某个值时,我们可以使用 indexOf() 方法。但有一种更好的方法,让我们来看一下这个例子。

//longhand
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) === -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

//按位 ( ~ ) 运算符将返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函数。

if (arr.includes(item)) { // 如果找到项目,则为true}

9.Object.entries()

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/

附上完整链接:https://mp.weixin.qq.com/s/uZpcgmDBTnO5ljGzJAhL2Q

不可错过的JS代码优化技巧(持续更新)的相关教程结束。

《不可错过的JS代码优化技巧(持续更新).doc》

下载本文的Word格式文档,以方便收藏与打印。