JavaScript 代码优化技巧

JavaScript 代码优化技巧

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

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}

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

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

2. If … else 的缩写法

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

// Shorthand
let test = (x > 10) ? true : false;

条件运算符(三元运算符):
语法形式:布尔表达式 ? 表达式1 :表达式2
运算过程:如果布尔表达式的值为 true ,则返回 表达式1 的值,否则返回 表达式2 的值

3. 聚合运算符

聚合运算符:xx ?? xx
意义:如果左值为 null 或 undefined,就返回右值。默认返回左值。

const test= null ?? 'default';
console.log(test);
// expected output: "default"const

test1 = 0 ?? 2;
console.log(test1);
// expected output: 0

4. 同时为多个变量赋值

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;

//Shorthand 
let [test1, test2, test3] = [1, 2, 3];

5. 判断变量是否存在的缩写法

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)

// Shorthand 
//it will check empty string,null and undefined too
if (test1){}

6. 用于多个条件的与(&&)运算符

// 变量为 true 时调用一个函数
//Longhand 
if (test1) {
 callMethod(); 
} 

//Shorthand 
test1 && callMethod();

7. for… 循环缩写法

// Longhand
for (var i = 0; i < testData.length; i++) {
   console.log(i,testData[i]);
}

// Shorthand
for (let i in testData){
   console.log(testData[i]);
}
// or
// for (let j of testData){
//   console.log(j);
// }

8. 找出一个数组中最大和最小的值

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

9. Object.values()

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

10. 获取一个随机布尔值 (true/false)

const randomBoolean = () => Math.random() >= 0.5;

console.log(randomBoolean());

// Result: a 50/50 change on returning true of false

Math.random()
该方法将在 0 和 1 之间创建一个随机数,之后我们检查它是否高于或低于 0.5。这意味着得到真或假的几率是 50%/50%。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值