js代码优化

1.获取对象属性值

const name = obj && obj.name

您可以在 ES6 中使用可选的链接运算符:

const name = obj?.name

2.判断输入框不为空

在日常开发中,无论PC端还是移动端,在处理与输入框相关的业务时,往往会判断输入框没有输入值。

if(value !== null && value !== undefined && value !== ''){
    //...
}

可以改进为:

if((value??'') !== ''){
  //...
}

3.异步函数

异步函数很常见

const fn1 = () =>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 300);
  });
}
const fn2 = () =>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(2);
    }, 600);
  });
}
const fn = () =>{
   fn1().then(res1 =>{
      console.log(res1);// 1
      fn2().then(res2 =>{
        console.log(res2)
      })
   })
};

改进后。

const fn = async () =>{
  const res1 = await fn1();
  const res2 = await fn2();
  console.log(res1);// 1
  console.log(res2);// 2
}

代码一下子简洁了许多,总算松了一口气。

如果是并发请求,可以使用Promise.all()

const fn = () =>{
   Promise.all([fn1(),fn2()]).then(res =>{
       console.log(res);// [1,2]
   }) 
}
  1. 使用 Async/Await 简化异步代码

Async/await 是一种简化 JavaScript 中异步代码处理的方法。它允许您以一种看起来和行为都像同步代码的方式编写异步代码。

async function getData() {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  const data = await response.json();
  console.log(data);
}
getData();

5.默认值

在未定义值的情况下,解构还可以将默认值分配给变量,例如:

const person = { name: 'John' };
let age = person.age || 25;

如果我们使用解构这样写代码更加简洁:

const person = { name: 'John' };
const { age = 25 } = person;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值