2024年前端开发者需要知道的34种JS优化技巧,作为前端程序员

test2 = (x > 100) ? ‘greater 100’ : (x < 50) ? ‘less 50’ : ‘between 50 and 100’;

console.log(test2); // “greater than 100”

3. 声明变量

当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。

//Longhand

let test1;

let test2 = 1;

//Shorthand

let test1, test2 = 1;

4. null、undefined 和空值检查

当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。

// Longhand

if (test1 !== null || test1 !== undefined || test1 !== ‘’) {

let test2 = test1;

}

// Shorthand

let test2 = test1 || ‘’;

5. null 检查和默认赋值

let test1 = null,

test2 = test1 || ‘’;

console.log(“null check”, test2); // output will be “”

6. undefined 检查和默认赋值

let test1 = undefined,

test2 = test1 || ‘’;

console.log(“undefined check”, test2); // output will be “”

一般值检查

let test1 = ‘test’,

test2 = test1 || ‘’;

console.log(test2); // output: ‘test’

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

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

const test= null ?? ‘default’;

console.log(test);

// expected output: “default”

const test1 = 0 ?? 2;

console.log(test1);

// expected output: 0

7. 给多个变量赋值

当我们想给多个不同的变量赋值时,这种技巧非常有用。

//Longhand

let test1, test2, test3;

test1 = 1;

test2 = 2;

test3 = 3;

//Shorthand

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

8. 简便的赋值操作符

在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。

// Longhand

test1 = test1 + 1;

test2 = test2 - 1;<

  • 20
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值