在工作中不可错过的JS代码优化技巧

平时在工作中不可错过的JS代码优化技巧,有利于CodeReview和代码成长~~

1. 使用 arr.includes 方法 代替 带有多个条件的 if 语句判断

//longhand
if(rightData.levelId=== -1 || rightData.levelId===0 || rightData.levelId===1 || rightData.levelId===2 || rightData.levelId===3) {
    //doing
}
//shorthand
if([-1, 0, 1, 2, 3].includes(rightData.levelId)){
   //doing
}

2. 使用三元运算 代替 if true...else

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}

// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
let test = x > 10;
console.log(test);
如果有嵌套的条件,可以这么做:
let x = 300,
test2 = (x > 100) ? 'greater than 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"

3. 查找数组的最大值和最小值

const arr = [1, 2, 3]; 
Math.max(...arr); // 3
Math.min(...arr); // 1

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

如果只在变量为 true 时才调用函数,可以使用 && 操作符。

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

5. for each 循环

这是一种常见的循环简化技巧。

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)

遍历数组的每一个变量。

function testData(element, index, array) {
  console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32

6. || 比较后返回

// Longhand
let test;
function checkReturn() {
    if (!(test === undefined)) {
        return test;
    } else {
        return callMe('test');
    }
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
    console.log(val);
}
// Shorthand
function checkReturn() {
    return test || callMe('test');
}

7. switch 简化

我们可以将条件保存在键值对象中,并根据条件来调用它们。

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // ...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();

8 隐式返回

通过使用箭头函数,我们可以直接返回值,不需要 return 语句。

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)

9. 默认参数值

//Longhand
function add(test1, test2) {
  if (test1 === undefined)
    test1 = 1;
  if (test2 === undefined)
    test2 = 2;
  return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //输出结果: 3

10. 延展操作符简化

//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]
我们也可以使用延展操作符进行克隆。

//longhand
// 克隆数组
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand
//克隆数组
const test1 = [1, 2, 3];
const test2 = [...test1];

11. 解构赋值

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

12. 数组 find 简化

当我们有一个对象数组,并想根据对象属性找到特定对象,find 方法会非常有用。

const data = [{
        type: 'test1',
        name: 'abc'
    },
    {
        type: 'test2',
        name: 'cde'
    },
    {
        type: 'test1',
        name: 'fgh'
    },
]
function findtest1(name) {
    for (let i = 0; i < data.length; ++i) {
        if (data[i].type === 'test1' && data[i].name === name) {
            return data[i];
        }
    }
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }

13. 条件查找简化

如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有没有比这更好的简化技巧呢?

// 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();

14. Object.entries()将对象转换为对象数组

Object.entries() 作用:将一个对象中可枚举属性的键名和键值按照二维数组的方式返回。
若对象是数组,则会将数组的下标作为键值返回。

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
//
[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]
Object.entries({ one: 1, two: 2 }) //[['one', 1], ['two', 2]]
Object.entries([1, 2])  //[['0', 1], ['1', 2]]

15. Object.values()获取对象value值

Object.values({})返回的是对象集合value值组成的数组

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);//[ 'abc', 'cde']

16. 使用str.repeat 重复字符串多次

为了重复操作相同的字符,我们可以使用 for 循环,但其实还有一种简便的方法。

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

17. 通过索引获取字符串指定位置字符

let str = 'abc';
//Longhand 
str.charAt(2); // c

//Shorthand 
str[2]; // c

18. null、undefined 和空值检查

当我们创建了新变量,有时候想要检查引用的变量是不是 非 null 或 undefined

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

19. null 检查和默认赋值

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // 输出 ""

20. undefined 检查和默认赋值

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // 输出 ""

//一般值检查
let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // 输出: 'test'

另外,对于上述的 4、5、6 点,都可以使用?? 操作符。

如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。

const test= null ?? 'default';
console.log(test);// 输出结果: "default"

const test1 = 0 ?? 2;
console.log(test1);
// 输出结果: 0

————————————————————————————

以后遇到了再进行补充~~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值