记录一下这些喜欢的新功能
因为JavaScript是动态类型的,所以在分配变量时,咱们须要牢记JavaScript对真值/假值的处理。 不少时候数字0
和空字符串''
就是咱们须要的值,咱们来看一下下面这个对象前端
双管道 ||
后端
let player = { profile: { number: 0, name: undefined, other: '' } }; console.log(player.profile.number || "未知"); // 未知 console.log(player.profile.name || "未知"); // 未知
双问号 ??
数组
let player = { profile: { number: 0, name: undefined, other: '' } }; console.log(player.profile.number ?? "未知"); // 0 console.log(player.profile.name ?? "未知"); // 未知
不少状况下前端从后端获取的数据中,并不肯定某个属性存不存在,因此会作个判断,若是不存在就给个默认值避免报错。promise
可是数字0
和空字符串''
一般会被“误伤”,好比nba球星威少、乐福、库兹马都是零号。安全
因此双问号能够更准确得去处理 null
和 undefined
异步
在点号以前加一个问号async
我太喜欢这个可选操做符了,和双问号殊途同归,配合使用安全加倍。
相信前端遇到过不少次这种错误:Cannot read property 'xxx' of undefined
有木有???!!!
有时候是粗心,有时候是拼错属性名,有时候就是后端数据返回有问题。
直接上代码:编辑器
不少时候会这样处理,看上去没什么问题函数
// 假设从后端返回的是一个空对象 let player = {}; console.log(player.profile.number || "未知") // Uncaught TypeError: Cannot read property 'number' of undefined
可选操做符,操做一下工具
let player = {}; console.log(player.profile.number ?? "23"); // player.profile is undefined` console.log(player.profile?.number ?? "23"); //23
假设你有一个utils工具文件,则其中某些功能可能不多使用,而导入其全部依赖项会很浪费资源。如今,咱们可使用 async
/ await
在须要时动态导入依赖项。
const add = (num1, num2) => num1 + num2; export { add };
const doMath = async (num1, num2) => { if (num1 && num2) { const math = await import('./math.js'); console.log(math.add(5, 10)); }; }; doMath(4, 2);
我在现实项目中就遇到过,好比回帖编辑器,不少人只是看一下别人的回复乐呵乐呵,用户不点击回帖,就不必去加载整个editor.js
const replyBtn = document.querySelector('#replyBtn') replyBtn.addEventListener('click', e => { e.preventDefault() (async () => { const Editor = await import('./editor.js') let editor = new Editor() })(); }) // 也能够 replyBtn.addEventListener('click', e => { e.preventDefault() import('/modules/editor.js') .then(Editor => { let editor = new Editor() }) .catch(err => { console.log(err) }); })
类的主要目的之一是将咱们的代码包含在可重用的模块中。 咱们可能会在不少地方用到这个类,有些属性并不但愿被类的外部访问。
如今,经过在变量或函数前面添加一个简单的哈希符号,咱们能够将它们彻底保留给类内部使用。
class People { #message = "湖人总冠军" bb() { console.log(this.#message) } } const p = new People() p.bb() // 湖人总冠军 console.log(p.#message) // Private name #message is not defined
当咱们处理多个Promise
时,尤为是当它们相互依赖时,经过Promise.allSettled
能够很好的记录调试或者获取每一个promise的状态结果,它会返回一个新的Promise
,仅当传递给它的全部Promise都完成时(settled 顾名思义能够理解成定居、稳定)才返回。 这将使咱们可以访问一个数组,其中包含每一个promise的一些数据。
相比于Promise.all
,若是传入的promise
中有一个失败(rejected),Promise.all
异步地将失败rejected
的那个结果给失败状态的回调函数,而无论其它promise
是否完成。
Promise.allSettled
会等全部传入的promise
的状态变为 fulfilled
或者 rejected
const p1 = new Promise((res, rej) => setTimeout(res, 1000, 24)); const p2 = new Promise((res, rej) => setTimeout(rej, 1000)); Promise.allSettled([p1, p2]).then(data => console.log(data)); // [ // Object { status: "fulfilled", value: 24}, // Object { status: "rejected", reason: undefined} // ]