Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the JavaScript optimization techniques?

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you what JavaScript optimization techniques are, which are concise and easy to understand, which can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

My motivation is to introduce all JavaScript best practices, such as shorthand and features, which we as front-end developers need to know to make our lives easier in 2021.

You may have been developing JavaScript for a long time, but sometimes you may not use the latest features that do not require solving or writing some extra code to solve the problem. These techniques can help you write clean and optimized JavaScript code. In addition, these topics can help you prepare for the JavaScript interview in 2021.

Here, I'll provide a new series of shorthand techniques that can help you write cleaner and optimized JavaScript code.

1. If there are multiple conditions

We can store multiple values in an array and we can use the array include method.

/ / longhand if (x = 'abc' | | x = =' def' | | x = = 'ghi' | | x =' jkl') {/ / logic} / / shorthand if (['abc',' def', 'ghi',' jkl']. Logic}) {/ / logic}

2.If true... Else abbreviation

This is a bigger shortcut when we have if-else conditions that don't contain more logic. We can simply use the ternary operator to achieve this shorthand.

/ / Longhand let test: boolean; if (x > 100) {test = true;} else {test = false;} / / Shorthand let test = (x > 10)? True: false; / / or we can use directly let test = x > 10; console.log (test)

When we have nesting conditions, we can use this approach.

Let x = 300, test2 = (x > 100)? 'greater 100': (X

< 50) ? 'less 50' : 'between 50 and 100'; console.log(test2); // "greater than 100" 3.声明变量 当我们要声明两个具有共同值或共同类型的变量时,可以使用此简写形式。 //Longhand let test1; let test2 = 1; //Shorthand let test1, test2 = 1; 4.空,未定义,空检查 当我们确实创建新变量时,有时我们想检查为其值引用的变量是否为null或未定义。JavaScript确实具有实现这些功能的非常好的捷径。 // Longhand if (test1 !== null || test1 !== undefined || test1 !== '') { let test2 = test1; } // Shorthand let test2 = test1 || ''; 5.空值检查和分配默认值 let test1 = null, test2 = test1 || ''; console.log("null check", test2); // output will be "" 6.未定义值检查和分配默认值 let test1 = undefined, test2 = test1 || ''; console.log("undefined check", test2); // output will be "" 正常值检查 let test1 = 'test', test2 = test1 || ''; console.log(test2); // output: 'test' (奖金:现在我们可以对主题4,5和6使用??运算符) 空位合并运算符 空合并运算符??如果左侧为null或未定义,则返回右侧的值。默认情况下,它将返回左侧的值。 const test= null ?? 'default'; console.log(test); // expected output: "default"const test1 = 0 ?? 2; console.log(test1); // expected output: 0 7.给多个变量赋值 当我们处理多个变量并希望将不同的值分配给不同的变量时,此速记技术非常有用。 //Longhand let test1, test2, test3; test1 = 1; test2 = 2; test3 = 3; //Shorthand let [test1, test2, test3] = [1, 2, 3]; 8.赋值运算符的简写 我们在编程中处理很多算术运算符。这是将运算符分配给JavaScript变量的有用技术之一。 // Longhand test1 = test1 + 1; test2 = test2 - 1; test3 = test3 * 20; // Shorthand test1++; test2--; test3 *= 20; 9.如果存在速记 这是我们大家都在使用的常用速记之一,但仍然值得一提。 // Longhand if (test1 === true) // Shorthand if (test1) 注意:如果test1有任何值,它将在if循环后进入逻辑,该运算符通常用于null或未定义的检查。 10.多个条件的AND(&&)运算符 如果仅在变量为true的情况下才调用函数,则可以使用&&运算符。 //Longhand if (test1) { callMethod(); } //Shorthand test1 && callMethod(); 11. foreach循环速记 这是迭代的常用速记技术之一。 // Longhand for (var i = 0; i < testData.length; i++) // Shorthand for (let i in testData) or for (let i of testData) 每个变量的数组 function testData(element, index, array) { console.log('test[' + index + '] = ' + element); } [11, 24, 32].forEach(testData); // logs: test[0] = 11, test[1] = 24, test[2] = 32 12.比较返回值 我们也可以在return语句中使用比较。它将避免我们的5行代码,并将它们减少到1行。 // Longhand let test; function checkReturn() { if (!(test === undefined)) { return test; } else { return callMe('test'); } } var data = checkReturn(); console.log(data); //output test function callMe(val) { console.log(val); } // Shorthand function checkReturn() { return test || callMe('test'); } 13.箭头函数 //Longhand function add(a, b) { return a + b; } //Shorthand const add = (a, b) =>

A + b

More examples.

Function callMe (name) {console.log ('Hello', name);} callMe = name = > console.log (' Hello', name)

14. Short function call

We can use ternary operators to achieve these functions.

/ / Longhand function test1 () {console.log ('test1');}; function test2 () {console.log (' test2');}; var test3 = 1; if (test3 = 1) {test1 ();} else {test2 ();} / Shorthand (test3 = 1? Test1:test2) ()

15.Switch shorthand

We can save the condition in the key value object and use it according to the condition.

/ / Longhand switch (data) {case 1: test1 (); break; case 2: test2 (); break; case 3: test (); break; / / And so on... } / / Shorthand var data = {1: test1, 2: test2, 3: test}; data [something] & & data [something] ()

16. Implicitly return shorthand

Using the arrowhead feature, we can return values directly without having to write return statements.

/ / longhand function calculate (diameter) {return Math.PI * diameter} / / shorthand calculate = diameter = > (Math.PI * diameter;)

17. Decimal index

/ / Longhand for (var I = 0; I

< 10000; i++) { ... } // Shorthand for (var i = 0; i < 1e4; i++) { 18.默认参数值 //Longhand function add(test1, test2) { if (test1 === undefined) test1 = 1; if (test2 === undefined) test2 = 2; return test1 + test2; } //shorthand add = (test1 = 1, test2 = 2) =>

(test1 + test2); add () / / output: 3

19. Shorthand of point difference operator

/ / longhand / / joining arrays using concat const data = [1,2,3]; const test = [4,5,6] .concat (data); / / shorthand / / joining arrays const data = [1,2,3]; const test = [4,5,6,... data]; console.log (test); / / [4,5,6,1,2,3]

For cloning, we can also use the propagation operator.

/ / longhand / / cloning arrays const test1 = [1,2,3]; const test2 = test1.slice () / / shorthand / / cloning arrays const test1 = [1,2,3]; const test2 = [. Test1]

20. Template text

If you are tired of using + to concatenate multiple variables in a single string, this shorthand will eliminate your headache.

/ / longhand const welcome ='Hi'+ test1 +''+ test2 +'. / / shorthand const welcome = `Hi ${test1} ${test2} `

21. Multiline string shorthand

When we work with multiple lines of strings in our code, we can use the following features:

/ / longhand const data = 'abc abc abc abc abc abc\ n\ t' + 'test test,test test test test\ n\ t' / / shorthand const data = `abc abc abc abc abc abc test test,test test test test`

twenty-two。 Object attribute assignment

Let test1 = 'averse; let test2 =' baked; / / Longhand let obj = {test1: test1, test2: test2}; / / Shorthand let obj = {test1, test2}

23. String into numbers

/ / Longhand let test1 = parseInt ('123'); let test2 = parseFloat (' 12.3'); / / Shorthand let test1 = + '123mm; let test2 = +' 12.3'

24. Distribution shorthand

/ / longhand const test1 = this.data.test1; const test2 = this.data.test2; const test2 = this.data.test3; / / shorthand const {test1, test2, test3} = this.data

25. Abbreviation for Array.find

The find method is really useful when we do have an array of objects and we want to find specific objects based on object properties.

Const data = [{type: 'test1', name:' abc'}, {type: 'test2', name:' cde'}, {type: 'test1', name:' fgh'},] function findtest1 (name) {for (let I = 0; I)

< data.length; ++i) { if (data[i].type === 'test1' && data[i].name === name) { return data[i]; } } } //Shorthand filteredData = data.find(data =>

Data.type = = 'test1' & & data.name = =' fgh'); console.log (filteredData); / / {type: 'test1', name:' fgh'}

twenty-six。 Find condition shorthand

If we have code to check the type and call different methods based on the type, we can choose to use multiple else if or switch, but what if our shorthand is better?

/ / Longhand if (type = 'test1') {test1 ();} else if (type =' test2') {test2 ();} else if (type = 'test3') {test3 ();} else if (type =' test4') {test4 ();} else {throw new Error ('Invalid value' + type);} / / Shorthand var types = {test1: test1, test2: test2, test3: test3, test4: test4}; var func = types [type] (! func) & & throw new Error ('Invalid value' + type); func ()

twenty-seven。 Shorthand bitwise index

When we iterate through the array to find a specific value, we do use the indexOf () method. What if we find a better way? Let's look at this example.

/ / longhand if (arr.indexOf (item) >-1) {/ / item found} if (arr.indexOf (item) = =-1) {/ / item not found} / / shorthand if (~ arr.indexOf (item)) {/ / item found} if (! ~ arr.indexOf (item)) {/ / item not found}

The bitwise (~) operator returns a real value that is not-1. Taking the reverse is as simple as doing it. Alternatively, we can use the include () function:

If (arr.includes (item)) {/ / true if the item found}

twenty-eight。 Object.entries ()

This feature helps you convert objects into an array of objects.

Const data = {test1: 'abc', test2:' cde', test3: 'efg'}; const arr = Object.entries (data); console.log (arr); / * Output: [[' test1', 'abc'], [' test2', 'cde'], [' test3', 'efg']] * /

twenty-nine。 Object.values ()

This is also a new feature introduced in ES8 that performs functions similar to Object.entries (), but with no key parts:

Const data = {test1: 'abc', test2:' cde'}; const arr = Object.values (data); console.log (arr); / * Output: ['abc',' cde'] * /

thirty。 Double Bitwise abbreviation

(the double NOT bitwise operator method applies only to 32-bit integers)

/ / Longhand Math.floor (1.9) = = 1 / / true / / Shorthand ~ 1.9 = = 1 / / true

thirty-one。 Repeat a string multiple times

To repeat the same characters over and over again, we can use for loops and add them to the same loop, but what if we have a shorthand method?

/ / longhand let test =''; for (let I = 0; I < 5; I + +) {test + = 'test';} console.log (str); / / test test test test test / / shorthand 'test' .repeat (5)

thirty-two。 Find the maximum and minimum values in the array

Const arr = [1,2,3]; Math.max (… Arr); / / 3 Math.min (… Arr); / / 1

thirty-three。 Get characters from a string

Let str = 'abc'; / / Longhand str.charAt (2); / c / / Shorthand Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefined str [2]; / / c

thirty-four。 Power shorthand

Abbreviation of mathematical exponential power function:

/ / longhand Math.pow (2 shorthand 3); / 8 / / shorthand 2 optimization 3 / / 8 what are the JavaScript optimization techniques mentioned above? have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report