In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the JavaScript optimization skills". In the daily operation, I believe many people have doubts about JavaScript optimization skills. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what are the JavaScript optimization skills?" Next, please follow the editor to study!
1. Judgment of multiple conditions
When we need to judge multiple values, we can use the includes method of the array.
/ / Badif (x = = 'iphoneX' | | x = =' iphone11' | | x = = 'iphone12') {/ / code... } / / Goodif (['iphoneX',' iphone11', 'iphone12'] .code... (x)) {/ / code...}
2. If true... Else
Trinomial operators are better when the if-else condition does not contain larger logic inside.
/ / Badlet test= boolean;if (x > 100) {test= true;} else {test= false;} / / Goodlet test= (x > 10)? True: false;//or we can simply uselet test = x > 10
After nesting the condition, we keep the following content (three items of complexity):
Let x = 300. Let test2 = (x > 100)? 'greater 100': (X
< 50) ? 'less 50' : 'between 50 and 100';console.log(test2); // "greater than 100" 3. Null、Undefined、'' 空值检查 有时要检查我们为值引用的变量是否不为null或Undefined 或 '' ,我们可以使用短路写法 // Badif (first !== null || first !== undefined || first !== '') {let second = first;}// Good 短路写法let second = first|| ''; 4. 空值检查和分配默认值 当我们赋值,发现变量为空需要分配默认值 可以使用以下短路写法 let first = null,let second = first || 'default'console.log(second) 4. 双位操作符 位操作符是 JavaScript 初级教程的基本知识点,但是我们却不常使用位操作符。因为在不处理二进制的情况下,没有人愿意使用 1 和 0。 但是双位操作符却有一个很实用的案例。你可以使用双位操作符来替代 Math.floor( )。双否定位操作符的优势在于它执行相同的操作运行速度更快 // BadMath.floor(4.9) === 4 //true// Good~~4.9 === 4 //true 5. ES6常见小优化 - 对象属性 const x,y = 5// Badconst obj = { x:x, y:y }// Goodconst obj = { x, y } 6. ES6常见小优化-箭头函数 //Badfunction sayHello(name) { console.log('Hello', name);}setTimeout(function() { console.log('Loaded')}, 2000)list.forEach(function(item) { console.log(item)})// Goodconst sayHello = name =>Console.log ('Hello', name) setTimeout (() = > console.log (' Loaded'), 2000) list.forEach (item = > console.log (item))
7. ES6 common minor optimizations-implicit return values
The return value is the keyword that we usually use to return the final result of the function. The arrow function with only one statement can implicitly return the result (the function must omit parentheses ({}) in order to omit the return keyword).
To return a multiline statement, such as object text, you need to wrap the function body with () instead of {}. This ensures that the code evaluates as a single statement.
/ / Badfunction calcCircumference (diameter) {return Math.PI * diameter} / / Goodconst calcCircumference = diameter = > (Math.PI * diameter)
8. ES6 common minor optimization-deconstruction assignment
Const form = {a form.bconst 1, b v v 2, c v v 3} / / Badconst a = form.aconst b = form.bconst c = form.c// Goodconst {a, b, c} = form
9. ES6 common minor optimizations-unfold operator
The return value is the keyword that we usually use to return the final result of the function. The arrow function with only one statement can implicitly return the result (the function must omit parentheses ({}) in order to omit the return keyword).
To return a multiline statement, such as object text, you need to wrap the function body with () instead of {}. This ensures that the code evaluates as a single statement.
Const odd = [1,3,5] const arr = [1,2,3,4] / / Badconst nums = [2,4,6] .concat (odd) const arr2 = arr.slice () / / Goodconst nums = [2,4,6,... odd] const arr2 = [. Arr]
10. Common array processing
Master the common methods of array, keep them in mind, don't read API while writing, this can effectively improve the coding efficiency, after all, these methods are used every day.
Every some filter map forEach find findIndex reduce includes
Const arr = [1Jing 2jue 3] / / every each item is valid before trueconsole.log (arr.every (it = > it > 0)) / / true//some is returned. It returns trueconsole.log (arr.some (it= > it > 2)) / / true//filter filter console.log (arr.filter (it= > it===2)) / / [2] / / map returns a new array console.log (arr.map (it= > it=== {id:it})) / / [{id:1}, {id:2} {id:3}] / / forEach does not return a value console.log (arr.forEach (it= > it===console.log (it)) / / undefined//find lookup corresponding value returns the new array console.log (arr.find (it= > it===it > 2)) / / 3//findIndex looks up the corresponding value and returns the subscript console.log (arr.findIndex (it= > it===it > 2) of the new array immediately after finding the corresponding value. / / 2//reduce summation or merge array console.log (arr.reduce ((prev) Cur) = > prev+cur)) / / 6//includes summation or merging array console.log (arr.includes (1)) / / true// array deduplicates const arr1 = [1mine2jing3jing3] const removeRepeat = (arr) = > [. New Set (arr1)] / / [1mai2 3] / / find the maximum value of Math.max (... arr) / / 3Math.min (... arr) / / 1ax / object deconstruction in this case, you can also use Object.assign instead of let defaultParams= {pageSize:1, sort:1} / / goods1let reqParams= {... defaultParams, sort:2} / / goods2Object.assign (defaultParams, {sort:2}).
11. Comparison return
Using comparisons in return statements reduces the code from 5 lines to 1 line.
/ / Badlet testconst checkReturn = () = > {if (test! = = undefined) {return test;} else {return callMe ('test');}} / / Goodconst checkReturn = () = > {return test | | callMe (' test');}
twelve。 Short function call
We can use ternary operators to implement such functions.
Const test1 = () = > {console.log ('test1');} const test2 = () = > {console.log (' test2');} const test3 = 1 else if (test3 = = 1) {test1 ()} else {test2 ()} / / Goodtest3 = = 1? Test1 (): test2 ()
13.switch Code Block (ifelse Code Block) shorthand
We can save the condition in the key-value object, and then we can use it according to the condition.
/ / Badswitch (data) {case 1: test1 (); break; case 2: test2 (); break; case 3: test (); break; / / And so on...} / / Goodconst data = {1: test1, 2: test2, 3: test} data [anything] & & data [anything] () / / Badif (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);} / / Goodconst types = {test1: test1, test2: test2, test3: test3, test4: test4}; const func = types [type]; (! func) & throw new Error ('Invalid value' + type); func ()
14. Multiline string abbreviation
When we deal with multiple lines of strings in our code, we can do this:
/ / Badconst data = 'abc abc abc abc abc abc\ n\ tasking +' test test,test test test test\ n\ tScallop / Goodconst data = `abc abc abc abc abc abc test test,test test test test`
15. Object.entries () Object.values () Object.keys ()
Object.entries () this feature converts an object into an array of objects.
Object.values () can get the value of the object
Object.keys () can get the object key value
Const data = {test1: 'abc', test2:' cde'} const arr1 = Object.entries (data) const arr2 = Object.values (data) const arr3 = Object.keys (data) / * * arr1 Output: [['test1',' abc'], ['test2',' cde'],] * / / * * arr2 Output: ['abc',' cde'] * / / * arr3 Output: ['test1',' test2'] * /
16. Repeat a string multiple times
To repeat the same characters multiple times, we can use for loops and add them to the same loop. How to abbreviate it?
/ / Bad let test =''; for (let I = 0; I < 5; I + +) {test + = 'test,';} console.log (str); / / test,test,test,test,test,//good console.log (' test,'.repeat (5))
17. The abbreviation of power
The good of the mathematical exponential power function is as follows:
/ / Bad Math.pow (2, 3) / / 8//good 2 / 3 / 8
18. Numeric separator
You can now easily separate numbers by using _. This will make it easier to deal with large amounts of data.
/ / old syntaxlet number = 98234567//new syntaxlet number = 98234 567
If you want to use the latest features of the latest version of JavaScript (ES2021/ES12), please check the following:
1.replaceAll (): returns a new string where all matching patterns are replaced by new substitutes.
2.Promise.any (): you need an iterating Promise object that returns a Promise with a value when a Promise is complete.
3.weakref: this object holds a weak reference to another object and does not prevent it from being garbage collected.
4.FinalizationRegistry: lets you request a callback when an object is garbage collected.
5. Private methods: modifiers for methods and accessors: private methods can be declared with #.
6. Logical operators: & & and | | operators.
7.Intl.ListFormat: this object enables language-sensitive list formatting.
8.Intl.DateTimeFormat: this object enables language-sensitive date and time formats.
At this point, the study of "what are the JavaScript optimization skills" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.