天天看點

7 個Javascript 小技巧

7 個Javascript 小技巧

英文 | https://medium.com/@aidan.hallett/7-javascript-quick-tricks-8f9a73671590

翻譯 | 楊小愛

1、控制台對象方法

雖然 console.log 幾乎在每個代碼庫中都無處不在,但實際上還有很多其他方法可以在控制台對象上調用。

想要在表格中顯示您的數組或對象,可以使用 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'   │
└─────────┴────────────┴─────────────┴───────────────┘      

您可以隻使用一個或多個參數調用 console.table() 。您可以自定義要檢視的列。

什麼時候需要那個定時器功能?想知道一段代碼需要多少時間?你可以使用console.time() & console.timeEnd()

您可以通過傳入一個字元串來命名每個計時器執行個體。

console.time("timer1");
console.time("timer2");
setTimeout(() => {
  console.timeEnd("timer1");
}, 1000);
// Output: 'timer1: 1005.445ms'


setTimeout(() => {
  console.timeEnd("timer2");
}, 2000);
// Output: 'timer2: 2005.025ms'      

想知道您控制台記錄了多少次内容?就可以使用console.count(),示例如下:

console.count('Hello');
// Hello: 1
console.count('Hello');
// Hello: 2
console.count('Hello');
// Hello: 3      

僅在某些内容為假時才列印?就可以使用console.assert()。

const age = 19;
console.assert(age > 17, "User is unable to drive");
// No logs
console.assert(age > 21, "User is below 21");
// Assertion failed: User is below 21      

2、array.sort()

我最近參與了一個項目,我們需要根據對象的類别以特定順序對數組中的對象進行排序。例如;如果我們想按食品類别訂購超市購物狂歡中的食品,我們可以使用這種排序方法輕松完成。

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和一些數組

繼續以食品購物主題為例,我們可以使用數組上的 filter 方法來過濾任何屬性。在我們的例子中,價格使用了過濾器,您隻需傳回一個布爾值是否應該包含它。filter 方法循環周遊數組中的所有項目。

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   │
// └─────────┴────────┴────────┴───────┘      

在上面的例子中,我們按價格過濾。例如; 對于 ham,表達式的計算結果為真正的布爾值,該項目将包含在修改後的數組中。

item.price > 4 // true      

另一方面,對于apples,表達式的計算結果為 false,是以它被排除在修改後的數組中。

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 54
const ageOfBrother = object?.family?.brother?.age;
console.log(`Age of Brother ${ageOfBrother}`); 
//Age of Brother undefined      

可選鍊允許您驗證和使用嵌套對象屬性,而無需确定每個父對象是否存在。在上面的例子中,我們可以擷取兄弟的年齡,如果屬性存在就指派。在可選鍊之前,我們必須先确定父節點是否存在;

const ageOfBrother = object.family && object.family.brother && object.family.brother.age;      

對于深度嵌套的屬性,這種連結顯然會變得很長。

顯然,沒有對象連結和沒有檢查子對象的父對象會導緻 TypeError;

const ageOfMother = object.family.mother.age;
                                         ^
TypeError: Cannot read property 'age' of undefined      

5、使用下劃線簡化數字

在 ES2021 中引入,現在可以使用下劃線分隔數字,以便于快速閱讀。

// ES2020
const oneMillion = 1000000;


// ES2021
const oneMillion = 1_000_000;      

6、String.prototype.replaceAll

到目前為止,人們需要使用帶有全局标志的正規表達式來替換給定字元串中的字元/單詞。

const result = 'Hello World'.replace(/\s/g, '-');
// result => 'Hello-World'      

現在我們可以簡單地使用 replaceAll 字元串方法。

const result = 'Hello World'.replaceAll(' ', '-');
// result => 'Hello-World'      

7、邏輯指派運算符

空指派運算符

在 ES2021 之前,我們可以使用三元運算符或 OR 來配置設定确定的可選類型變量(即可能有也可能沒有值的變量);

使用三元運算符

// Using Ternary Operator
let template;
console.log(template);
// undefined
template = template != null ? template : 'default';
console.log(template);
// default      

使用 If 語句

// Using If statement
let template;
console.log(template);
// undefined
if (template == null) {
  template = 'default';
}
console.log(template);
// default      

但在使用ES2021,它的任務要簡單得多;

let template;
console.log(template);
// undefined
template ??= 'default';
console.log(template);
// default      

邏輯 OR 指派運算符

邏輯 OR 指派運算符的工作方式與 Nullish 指派運算符類似,不同之處在于它不是 null 或 undefined,而是在變量的計算結果為 false 時,将其指派給給定的變量。

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 指派運算符

如果變量的計算結果為真值,則邏輯 AND 指派運算符會配置設定一個值。

let user = {id: 18, first_name: "Aidan" };
user &&= {...user, loggedIn: true };
console.log(user);
// {id: 18, first_name: "Aidan", loggedIn: true}      

總結