×

收藏JavaScript中一些常用的代码性能优化技术【下篇】

作者:Terry2019.12.04来源:Web前端之家浏览:8857评论:0
关键词:js性能优化

500.jpg

昨天我们谈到了关于Javascript代码简写和性能的话题:收藏JavaScript中一些常用的代码性能优化技术【上篇】,今天我们继续分享下篇。OK,废话不多说,直接开始,GOOOOO!

13.销毁分配速记

如果您正在使用任何流行的Web框架,则很有可能会使用对象文字形式的数组或数据在组件和API之间传递信息。数据对象到达组件后,您需要解压缩它。

完整码:

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

速记:

import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;

您甚至可以分配自己的变量名:

const { store, form, loading, errors, entity:contact } = this.props;

14.多行字符串速记

如果您发现自己需要在代码中编写多行字符串,则可以这样编写:

完整版:

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

但是,有一种更简单的方法。只需使用反引号即可。

速记:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

15.点差运算符速记

ES6中引入的散布运算符具有多个用例,这些用例使JavaScript代码更加高效和有趣。它可以用来替换某些数组函数。扩展算子只是三个点的序列。

长手

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

速记:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

与该concat()函数不同,可以使用传播运算符在另一个数组内的任何位置插入一个数组。

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

您还可以将传播算子与ES6解构符号结合使用:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16.强制参数速记

默认情况下,JavaScript会将函数参数设置为undefined如果未传递值。其他一些语言将引发警告或错误。要强制进行参数分配,可以在时使用if语句引发错误undefined,或者可以利用“必填参数速记”。

完整版:

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

速记:

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}

17. Array.find速记

如果您曾被要求使用纯JavaScript编写find函数,那么您可能会使用for循环。在ES6中,find()引入了一个名为的新数组函数。


完整版:

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},]function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
}}

速记:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18.对象[键]速记

您知道吗,Foo.bar也可以写成Foo['bar']?首先,似乎没有理由应该这样写。但是,此符号为您提供了编写可重用代码的基础。

考虑以下简化的验证功能示例:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

此功能可以完美地完成其工作。但是,请考虑以下情况:您有很多表单需要应用验证,但是具有不同的字段和规则。构建可以在运行时配置的通用验证功能不是很好吗?

速记:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}


console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

现在我们有了一个验证函数,我们可以在所有形式中重复使用,而无需为每种形式编写自定义验证函数。

19. Double Bitwise NOT简写

按位运算符是您在初学者JavaScript教程中了解的功能之一,而您永远无法在任何地方实现它们。此外,如果您不处理二进制,谁愿意使用1和0?

但是,Double Bitwise NOT运算符有一个非常实用的用例。您可以用它代替Math.floor()。Double Bitwise NOT运算符的优点是执行相同操作的速度更快。

完整版:

Math.floor(4.9) === 4  //true

速记:

~~4.9 === 4  //true

20.指数幂速记

数学指数幂函数的简写:

完整版:

Math.pow(2,3); // 8Math.pow(2,2); // 4Math.pow(4,3); // 64

速记:

2**3 // 8
2**4 // 4
4**3 // 64

21.将字符串转换为数字

有时,您的代码会收到字符串格式的数据,但需要以数字格式进行处理。没什么大不了的,我们可以执行快速转换。

完整版:

const num1 = parseInt("100");
const num2 =  parseFloat("100.01");

速记:

const num1 = +"100"; // converts to int data type
const num2 =  +"100.01"; // converts to float data type

22.对象属性分配

考虑以下代码:

let fname = { firstName : 'Black' };
let lname = { lastName : 'Panther'}

您如何将它们合并为一个对象?一种方法是编写一个将数据从第二个对象复制到第一个对象的函数。不幸的是,这可能不是您想要的-您可能需要创建一个全新的对象而不更改任何现有对象。最简单的方法是使用Object.assignES6中引入的功能:

let full_names = Object.assign(fname, lname);

您还可以使用ES8中引入的对象破坏符号:

let full_names = {...fname, ...lname};

可以合并的对象属性的数量没有限制。如果确实具有具有相同属性名称的对象,则值将按照它们被合并的顺序被覆盖。

23.速记按位索引

使用数组执行查找时,该indexOf()函数用于检索要查找的项目的位置。如果找不到该项目,-1则返回该值。在JavaScript中,数字0被认为是“虚假的”,而大于或小于数字0则被认为是“真实的”。结果,必须编写这样的正确代码。

完整版:

if(arr.indexOf(item) > -1) { // Confirm item IS found

}

if(arr.indexOf(item) === -1) { // Confirm item IS NOT found

}

速记:

if(~arr.indexOf(item)) { // Confirm item IS found

}

if(!~arr.indexOf(item)) { // Confirm item IS NOT found

}

除了以外,bitwise(~)运算符将返回真实值-1。否定它就像这样做一样简单!~。另外,我们也可以使用以下includes()功能:

if(arr.includes(item)) { // Returns true if the item exists, false if it doesn't

}

24. Object.entries()

这是ES8中引入的一项功能,使您可以将文字对象转换为键/值对数组。请参阅以下示例:

const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.entries(credits);
console.log(arr);

/** Output:
[ [ 'producer', 'John' ],
  [ 'director', 'Jane' ],
  [ 'assistant', 'Peter' ]
]
**/

25. Object.values()

这也是ES8中引入的新功能,其功能与相似Object.entries(),但没有关键部分:

const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.values(credits);
console.log(arr);

/** Output:
[ 'John', 'Jane', 'Peter' ]
**/

总结

关于JavaScript中一些常用的代码性能优化技术,已经分享完毕,希望能帮助到大家,如有问题可以加群讨论或者留言。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/jsuw823948209384.html

网友评论文明上网理性发言 已有0人参与

发表评论: