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 optimization techniques of JavaScript abbreviation?

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

Share

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

What are the JavaScript shorthand optimization techniques? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

The life of a developer is always learning new things, and it shouldn't be harder to keep up with changes than it is now. My motivation is to introduce all the best practices of JavaScript, such as shorthand features. As a front-end developer, we must know to make our life easier in 2021.

You may have been working on JavaScript for a long time, but sometimes you may not update the latest features that can solve your problems without having to do or write some extra code. 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.

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}

two。 If it's true... Otherwise, abbreviated.

This is a big shortcut when we have if-else conditions and there is no larger logic in it. We can simply use the ternary operator to implement this abbreviation.

/ / 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, Undefined,空检查 当我们创建新的变量时,有时我们想检查我们引用的变量的值是否为空或undefined。JavaScript确实有一个非常好的简写工具来实现这些功能。 // Longhand if (test1 !== null || test1 !== undefined || test1 !== '') { let test2 = test1; } // Shorthand let test2 = test1 || ''; 5.null值检查和分配默认值 let test1 = null, test2 = test1 || ''; console.log("null check", test2); // output will be "" 6.undefined值检查和分配默认值 let test1 = undefined, test2 = test1 || ''; console.log("undefined check", test2); // output will be "" 正常值检查 let test1 = 'test', test2 = test1 || ''; console.log(test2); // output: 'test' 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) or if (test1 !== "") or if (test1 !== null) // Shorthand //it will check empty string,null and undefined too if (test1) 注意:如果test1有任何值,它将在if循环后进入逻辑,该运算符主要用于 null 或 undefined 的检查。 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中比较 我们也可以在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 abbreviation

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. Implicit return abbreviation

Using the arrow function, we can return the value directly without having to write a return statement.

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

17. Decimal base 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. Extension operator abbreviation

/ / 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 extension 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 can eliminate your headache.

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

21. Multiline string abbreviation

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. Convert a string to a number

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

24. Use deconstructed abbreviations

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

25. Abbreviated in 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。 Search condition abbreviation

If we have code to check the type and call different methods according to the type, we can choose to use multiple else ifs or switch, but what if we have a better shorthand method?

/ / 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。 Bitwise index abbreviation

When we walk 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}

Bitwise (?) The operator returns the true value of any value except-1. Denying it is as simple as doing it. Alternatively, we can use the include () function:

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

28.Object.entries ()

This function helps you convert an object to 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']] * /

29.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 is only applicable 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。 The abbreviation of mathematical exponential power function

/ / longhand Math.pow (2jue 3); / / 8 / shorthand 2 shorthand optimization 3 / / 8 the answers to the questions about JavaScript abbreviation optimization technology are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

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