天天看点

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}      

总结