7 個(gè)Javascript 小技巧

英文 | https://medium.com/@aidan.hallett/7-javascript-quick-tricks-8f9a73671590
翻譯 | 楊小愛(ài)
1、控制臺(tái)對(duì)象方法
雖然 console.log 幾乎在每個(gè)代碼庫(kù)中都無(wú)處不在,但實(shí)際上還有很多其他方法可以在控制臺(tái)對(duì)象上調(diào)用。
想要在表格中顯示您的數(shù)組或?qū)ο螅梢允褂?console.table()。
const users = [{"first_name":"Harcourt","last_name":"Huckerbe","gender":"Male","city":"Linchen","birth_country":"China"},{"first_name":"Allyn","last_name":"McEttigen","gender":"Male","city":"Ambelókipoi","birth_country":"Greece"},{"first_name":"Sandor","last_name":"Degg","gender":"Male","city":"Mthatha","birth_country":"South Africa"}]console.table(users, ['first_name', 'last_name', 'city']);┌─────────┬────────────┬─────────────┬───────────────┐│ (index) │ first_name │ last_name │ city |├─────────┼────────────┼─────────────┼───────────────┤│ 0 │ 'Harcourt' │ 'Huckerbe' │ 'Linchen' ││ 1 │ 'Allyn' │ 'McEttigen' │ 'Ambelókipoi' ││ 2 │ 'Sandor' │ 'Degg' │ 'Mthatha' │└─────────┴────────────┴─────────────┴───────────────┘
您可以只使用一個(gè)或多個(gè)參數(shù)調(diào)用 console.table() 。您可以自定義要查看的列。
什么時(shí)候需要那個(gè)定時(shí)器功能?想知道一段代碼需要多少時(shí)間?你可以使用console.time() & console.timeEnd()
您可以通過(guò)傳入一個(gè)字符串來(lái)命名每個(gè)計(jì)時(shí)器實(shí)例。
console.time("timer1");console.time("timer2");setTimeout(() => {console.timeEnd("timer1");}, 1000);// Output: 'timer1: 1005.445ms'setTimeout(() => {console.timeEnd("timer2");}, 2000);// Output: 'timer2: 2005.025ms'
想知道您控制臺(tái)記錄了多少次內(nèi)容?就可以使用console.count(),示例如下:
console.count('Hello');// Hello: 1console.count('Hello');// Hello: 2console.count('Hello');// Hello: 3
僅在某些內(nèi)容為假時(shí)才打印?就可以使用console.assert()。
const age = 19;console.assert(age > 17, "User is unable to drive");// No logsconsole.assert(age > 21, "User is below 21");// Assertion failed: User is below 21
2、array.sort()
我最近參與了一個(gè)項(xiàng)目,我們需要根據(jù)對(duì)象的類(lèi)別以特定順序?qū)?shù)組中的對(duì)象進(jìn)行排序。例如;如果我們想按食品類(lèi)別訂購(gòu)超市購(gòu)物狂歡中的食品,我們可以使用這種排序方法輕松完成。
const order = ["MEAT", "VEGETABLES", "FRUIT", "SNACKS"];const items = [{ name: "peppers", type: "VEGETABLES", price: 2.39 },{ name: "apples", type: "FRUIT", price: 3.99 },{ name: "chocolate", type: "SNACKS", price: 3.45 },{ name: "pork", type: "MEAT", price: 6 },{ name: "ham", type: "MEAT", price: 4 }];items.sort((a, b) => {return order.indexOf(a.type) > order.indexOf(b.type);});console.table(items, ["type", "name"]);// ┌─────────┬──────────────┬─────────────┐// │ (index) │ type │ name │// ├─────────┼──────────────┼─────────────┤// │ 0 │ 'MEAT' │ 'pork' │// │ 1 │ 'MEAT' │ 'ham' │// │ 2 │ 'VEGETABLES' │ 'peppers' │// │ 3 │ 'FRUIT' │ 'apples' │// │ 4 │ 'SNACKS' │ 'chocolate' │// └─────────┴──────────────┴─────────────┘
3、Filter,every和一些數(shù)組
繼續(xù)以食品購(gòu)物主題為例,我們可以使用數(shù)組上的 filter 方法來(lái)過(guò)濾任何屬性。在我們的例子中,價(jià)格使用了過(guò)濾器,您只需返回一個(gè)布爾值是否應(yīng)該包含它。filter 方法循環(huán)遍歷數(shù)組中的所有項(xiàng)目。
const order = ["MEAT", "VEGETABLES", "FRUIT", "SNACKS"];let items = [{ name: "peppers", type: "VEGETABLES", price: 2.39 },{ name: "apples", type: "FRUIT", price: 3.99 },{ name: "chocolate", type: "SNACKS", price: 3.45 },{ name: "pork", type: "MEAT", price: 6 },{ name: "ham", type: "MEAT", price: 7 }];items = items.filter(item => {return item.price > 4;});console.table(items);// ┌─────────┬────────┬────────┬───────┐// │ (index) │ name │ type │ price │// ├─────────┼────────┼────────┼───────┤// │ 0 │ 'pork' │ 'MEAT' │ 6 │// │ 1 │ 'ham' │ 'MEAT' │ 7 │// └─────────┴────────┴────────┴───────┘
在上面的例子中,我們按價(jià)格過(guò)濾。例如; 對(duì)于 ham,表達(dá)式的計(jì)算結(jié)果為真正的布爾值,該項(xiàng)目將包含在修改后的數(shù)組中。
item.price > 4 // true另一方面,對(duì)于apples,表達(dá)式的計(jì)算結(jié)果為 false,因此它被排除在修改后的數(shù)組中。
4、可選鏈
const object = {family: {father: {age: 54},sister: {age: 16}}}const ageOfFather = object.family.father.age;console.log(`Age of Father ${ageOfFather}`);//Age of Father 54const ageOfBrother = object?.family?.brother?.age;console.log(`Age of Brother ${ageOfBrother}`);//Age of Brother undefined
可選鏈允許您驗(yàn)證和使用嵌套對(duì)象屬性,而無(wú)需確定每個(gè)父對(duì)象是否存在。在上面的例子中,我們可以獲取兄弟的年齡,如果屬性存在就賦值。在可選鏈之前,我們必須先確定父節(jié)點(diǎn)是否存在;
const ageOfBrother = object.family && object.family.brother && object.family.brother.age;對(duì)于深度嵌套的屬性,這種鏈接顯然會(huì)變得很長(zhǎng)。
顯然,沒(méi)有對(duì)象鏈接和沒(méi)有檢查子對(duì)象的父對(duì)象會(huì)導(dǎo)致 TypeError;
const ageOfMother = object.family.mother.age;^TypeError: Cannot read property 'age' of undefined
5、使用下劃線簡(jiǎn)化數(shù)字
在 ES2021 中引入,現(xiàn)在可以使用下劃線分隔數(shù)字,以便于快速閱讀。
// ES2020const oneMillion = 1000000;// ES2021const oneMillion = 1_000_000;
6、String.prototype.replaceAll
到目前為止,人們需要使用帶有全局標(biāo)志的正則表達(dá)式來(lái)替換給定字符串中的字符/單詞。
const result = 'Hello World'.replace(/\s/g, '-');// result => 'Hello-World'
現(xiàn)在我們可以簡(jiǎn)單地使用 replaceAll 字符串方法。
const result = 'Hello World'.replaceAll(' ', '-');// result => 'Hello-World'
7、邏輯賦值運(yùn)算符
空賦值運(yùn)算符
在 ES2021 之前,我們可以使用三元運(yùn)算符或 OR 來(lái)分配確定的可選類(lèi)型變量(即可能有也可能沒(méi)有值的變量);
使用三元運(yùn)算符
// Using Ternary Operatorlet template;console.log(template);// undefinedtemplate = template != null ? template : 'default';console.log(template);// default
使用 If 語(yǔ)句
// Using If statementlet template;console.log(template);// undefinedif (template == null) {template = 'default';}console.log(template);// default
但在使用ES2021,它的任務(wù)要簡(jiǎn)單得多;
let template;console.log(template);// undefinedtemplate ??= 'default';console.log(template);// default
邏輯 OR 賦值運(yùn)算符
邏輯 OR 賦值運(yùn)算符的工作方式與 Nullish 賦值運(yùn)算符類(lèi)似,不同之處在于它不是 null 或 undefined,而是在變量的計(jì)算結(jié)果為 false 時(shí),將其賦值給給定的變量。
const user = {id: 18, first_name: "Aidan"};console.log(user);// {id: 18, first_name: "Aidan"}if(!user.profile_picture) {user.profile_picture = "https://picsum.photos/id/237/200/300" ;}console.log(user);// {id: 18, first_name: "Aidan", profile_picture: "https://picsum.photos/id/237/200/300"}
邏輯 AND 賦值運(yùn)算符
如果變量的計(jì)算結(jié)果為真值,則邏輯 AND 賦值運(yùn)算符會(huì)分配一個(gè)值。
let user = {id: 18, first_name: "Aidan" };user &&= {...user, loggedIn: true };console.log(user);// {id: 18, first_name: "Aidan", loggedIn: true}
總結(jié)
以上就是我今天與您分享的內(nèi)容,希望對(duì)您有所幫助,感謝您的閱讀,祝編程愉快!
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

