【2021 第一期】日常开发 26 个常见的 JavaScript 代码优化方案

小鹿 2021-02-23 09:48:06
第一 日常 第一期 常开 一期


大伙儿好~,我是小鹿,公众号:「小鹿动画学编程」 原创作者。

时隔半年我又回来了,期间发生了很多事情。从大学刚毕业来到一线找工作,也由于今年出现的特殊情况,文章断就更了一段时间。嗯~,就不给自己找借口啦。现在全部安顿好了,把精力开始慢慢回归到写作上,希望在 2021 新的一年和大伙儿一起在社区成长!


2021 第一期。

本篇文章整理了在日常开发中 26 个常见的 JavaScript 代码优化方案。

本文章已在 Github blog 收录,欢迎大伙儿~ Star,文章中若存在不足或者 issues,欢迎在下方或 Github 留言!

1、NullUndefined''检查

我们在创建新变量赋予一个存在的变量值的时候,并不希望赋予 nullundefined,我们可以采用一下简洁的赋值方式。

if(test !== null || test !== undefined || test !== ''){
let a1 = test;
}
// 优化后
let a1 = test || ''

2、null 值检查并赋予默认值

let test = null;
let a1 = test || '';

3、undefined 值检查并赋予默认值

let test = undefined;
let a1 = test || '';

4、空值合并运算符(??

空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

const test= null ?? 'default string';
console.log(test);
console.log(foo); // expected output: "default string"
const test = 0 ?? 42;
console.log(test); // expected output: 0

具体介绍可戳这 MDN

5、声明变量

当我们想要声明多个共同类型或者相同值的变量时,我们可以采用一下简写的方式。

let test1;
let test2 = 0;
// 优化后
let test1, test2 = 0;

6、if 多条件判断

当我们进行多个条件判断时,我们可以采用数组 includes 的方式来实现简写。

if(test === '1' || test === '2' || test === '3' || test === '4'){
// 逻辑
}
// 优化后
if(['1','2','3','4'].includes(test)){
// 逻辑处理
}

7、if...else 的简写

当存在一层或两层 if...else嵌套时,我们可以使用三元运算符来简写。

let test = null;
if(a > 10) {
test = true;
} else {
test = false;
}
// 优化后
let test = a > 10 ? true : false;
// 或者
let test = a > 10;

8、多变量赋值

当我们想给多个变量赋不同的值的时候,我们可以采用一下简洁的速记方案。

let a = 1;
let b = 2;
let c = 3;
// 优化
let [a, b, c] = [1, 2, 3];

9、算术运算简写优化

当我们在开发中经常用到算数运算符时,我们可以使用一下方式进行优化和简写。

let a = 1;
a = a + 1;
a = a - 1;
a = a * 2;
// 优化
a++;
a--;
a *= 2;

10、有效值判断

我们经常会在开发中用到的,在这也简单整理一下。

if (test1 === true)
if (test1 !== "")
if (test1 !== null)
// 优化
if (test1)

11、多条件(&&)判断

我们通常在项目中遇到条件判断后跟函数执行,我们可以使用一下简写方式。

if (test) {
foo();
}
//优化
test && foo();

12、多个比较 return

在 return 的语句中使用比较,可以将其进行缩写的形式如下。

let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return foo('test');
}
}
// 优化
function checkReturn() {
return test || foo('test');
}

13、Switch 的缩写

遇到如下形式的 switch 语句,我们可以将其条件和表达式以键值对的形式存储。

switch (type) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// ......
}
// 优化
var obj = {
1: test1,
2: test2,
3: test
};
obj[type] && obj[type]();

14、for 循环缩写

for (let i = 0; i < arr.length; i++)
// 优化
for (let i in arr) or for (let i of arr)

15、箭头函数

function add() {
return a + b;
}
// 优化
const add = (a, b) => a + b;

16、短函数调用

function fn1(){
console.log('fn1');
}
function fn2(){
console.log('fn2');
}
if(type === 1){
fn1();
}else{
fn2();
}
// 优化
(type === 1 ? fn1 : fn2)();

17、数组合并与克隆

const data1 = [1, 2, 3];
const data2 = [4 ,5 , 6].concat(data1);
// 优化
const data2 = [4 ,5 , 6, ...data1];

数组克隆:

const data1 = [1, 2, 3];
const data2 = test1.slice()
// 优化
const data1 = [1, 2, 3];
const data2 = [...data1];

18、字符串模版

const test = 'hello ' + text1 + '.'
// 优化
const test = `hello ${text}.` 

19、数据解构

const a1 = this.data.a1;
const a2 = this.data.a2;
const a3 = this.data.a3;
// 优化
const { a1, a2, a3 } = this.data;

20、数组查找特定值

数组按照索引来查找特定值,我们可以通过逻辑位运算符 来代替判断。

“~”运算符(位非)用于对一个二进制操作数逐位进行取反操作
if(arr.indexOf(item) > -1)
// 优化
if(~arr.indexOf(item))
// 或
if(arr.includes(item))

21、Object.entries()

const data = { a1: 'abc', a2: 'cde', a3: 'efg' };
Object.entries(data);
/** 输出:
[ [ 'a1', 'abc' ],
[ 'a2', 'cde' ],
[ 'a3', 'efg' ]
]
**/

22、Object.values()

我们可以通过 Object.values() 将对象的内容转化为数组。如下:

const data = { a1: 'abc', a2: 'cde' };
Object.values(data);
/** 输出:
[ 'abc', 'cde']
**/

23、求平方

Math.pow(2,3);
// 优化
2**3;

24、指数简写

for (var i = 0; i < 10000; i++)
// 优化
for (var i = 0; i < 1e4; i++) {

25、对象属性简写

let key1 = '1';
let key2 = 'b';
let obj = {key1: key1, key2: key2};
// 简写
let obj = {
key1,
key2
};

26、字符串转数字

let a1 = parseInt('100');
let a2 = parseFloat('10.1');
// 简写
let a1 = +'100';
let a2 = +'10.1';


️ 欢迎素质三连[点赞 + 收藏 + 评论]</font>

我是小鹿,文章同步更新 Github,也可以在微信搜一搜「 小鹿动画学编程」第一时间接收文章更新通知,回复“ 前端”可获取小鹿整理的备战面试小册。
版权声明
本文为[小鹿]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000039257887

  1. How to build a high performance front end intelligent reasoning engine
  2. How to become a professional front end engineer in 2021?
  3. How to transform single / micro service application into serverless application
  4. How to transform single / micro service application into serverless application
  5. How to transform single / micro service application into serverless application
  6. How to connect the ground gas to the micro front end?
  7. How to connect the ground gas to the micro front end?
  8. How to connect the ground gas to the micro front end?
  9. Vue server rendering principle analysis and introduction
  10. Realize the correct loading of text message
  11. Building my own project scaffolding with yeoman
  12. JavaScript advanced prototype and prototype chain
  13. React background management front end system (based on open source framework development) start
  14. JS practical skills breakpoint debugging
  15. I'd like to share with you 20 super easy-to-use Chrome extension plug-ins
  16. Get page element location
  17. Use the powerful API of modern browser to record any interface in the browser and realize export, save and management
  18. Delayed code execution in flutter
  19. Reconfiguration experience of KOA middleware system
  20. Add comments to your blog
  21. Svg editor -- new path
  22. Detailed explanation of debounce and throttle of JavaScript function
  23. Anti shake and throttling and corresponding react hooks package
  24. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  25. Front end, school recruitment, Taobao, guide
  26. [vue2 & G6] get started quickly
  27. Canvas from the beginning to the pig
  28. Take five minutes to standardize the code comments?
  29. Some thoughts on sass
  30. what?! You haven't filled in the award information yet
  31. How to get the interface + tsdoc needed by TS through swagger
  32. Binary tree
  33. Canvas drawing method in Web screenshot
  34. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  35. Become a big influence of technology? Coding pages quickly build personal blog
  36. Object and array deconstruction, spread operator, rest operator
  37. Analysis of Axios source code
  38. Two ways to delete useless code in project (Practical)
  39. Edit your picture with canvas
  40. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone
  41. JS mechanism 3: stack, heap, garbage collection
  42. [grid compression evaluation] meshquan, meshopt, Draco
  43. Deep understanding of Vue modifier sync [Vue sync modifier example]
  44. WebView for front end engineers
  45. React form source code reading notes
  46. Deep thinking about modern package manager -- why do I recommend pnpm instead of NPM / yarn?
  47. On the sequence of event capture and event bubbling
  48. Help you build a systematic understanding of the front end scaffolding
  49. commander.js Principle analysis
  50. Common usage of nginx
  51. H5 jump to wechat app
  52. Front end algorithm interview must brush questions series [14]
  53. Thinking of cross end practice
  54. Vue server rendering principle analysis and introduction
  55. [KT] vscode plug in development example series (2)
  56. Design ideas of react and Vue framework
  57. JavaScript String.prototype.replaceAll 兼容性导致的问题
  58. JavaScript String.prototype.replaceAll Problems caused by compatibility
  59. 爱奇艺体育:体验Serverless极致扩缩容,资源利用率提升40%
  60. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%