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]
})
}
- 使用 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;