In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
JavaScript shorthand skills, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
Shorthand skills in any programming language will help you write better and clearer code. With shorthand skills, you can not only improve the readability of the code, but also write less code to complete the task. Here are some shorthand tips for JavaScript.
1. Declare variable
/ / Longhand let x; let y = 20; / / Shorthand let x, y = 20
two。 Assign values to multiple variables
Multiple variables can be assigned values at the same time in one line of code.
/ / Longhand let marks = 26; let result; if (marks > = 30) {result = 'Pass';} else {result =' Fail';} / / Shorthand let result = marks > = 30? 'Pass': 'Fail'
3. Ternary operator
Using the ternary operator (condition), five lines of code can be reduced to one line.
/ / Longhand let imagePath; let path = getImagePath (); if (path! = = null & & path! = = undefined & & path! = ='') {imagePath = path;} else {imagePath = 'default.jpg';} / / Shorthand let imagePath = getImagePath () | |' default.jpg'
4. Assign default values
We can use the OR (| |) short-circuit assessment to specify a default value for the variable in case the expected value is empty.
/ / Longhand let imagePath; let path = getImagePath (); if (path! = = null & & path! = = undefined & & path! = ='') {imagePath = path;} else {imagePath = 'default.jpg';} / / Shorthand let imagePath = getImagePath () | |' default.jpg'
5. AND (& &) short circuit evaluation
If you need to call a function only if the variable is true, you can do it in one line using the AND (&) short-circuit evaluation.
/ / Longhand if (isLoggedin) {goToHomepage ();} / Shorthand isLoggedin & & goToHomepage ()
In shorthand, goToHomepage () is executed only if the result returned by isLoggedin is true.
6. Swap two variables
Usually exchanging two variables requires the help of a third variable. However, through array destructing assignments, you can easily exchange two variables.
/ / Longhand console.log ('You got a missed call from' + number +'at'+ time); / / Shorthand console.log (`You got a missed call from ${number} at ${time} `)
7. Arrowhead function
/ / Longhand function add (num1, num2) {return num1 + num2;} / / Shorthand const add = (num1, num2) = > num1 + num2
8. Template text
We usually use the "+" operator to concatenate string values and variables. With the ES6 template, we can do it in a simpler way.
/ / Longhand console.log ('JavaScript, often abbreviated as JS, is a\ n' +' programming language thatconforms to the\ n' + 'ECMAScript specification. JavaScript is high-level,\ n' +' often just-in-time compiled, and multi-paradigm.'); / / Shorthand console.log (`JavaScript, often abbreviated as JS, is a programming languagethat conforms to the ECMAScript specification. JavaScript is high-level, oftenjust-in-time compiled, and multi- paradigm.`)
9. Multiline string
For multiline strings, we usually use the "+" operator and the newline escape character (\ n) to concatenate. However, you can use "`" to simplify the code.
Let firstname = 'Amitav'; let lastname =' Mishra'; / / Longhand let obj = {firstname: firstname, lastname: lastname}; / / Shorthand let obj = {firstname, lastname}
10. Multiple conditional check
For multi-valued matching, you can put all the values in an array and use the indexOf () or includes () methods.
/ / Longhand if (value = 1 | | value = 'one' | | value = 2 | | value =' two') {/ / Execute some code} / / Shorthand 1 if ([1, 'one', 2,' two'] .indexOf (value) > = 0) {/ / Execute some code} / / Shorthand 2 if ([1, 'one', 2,' two'] .index1 (value)) {/ / Execute some code}
11. Object attribute assignment
If the variable name is the same as the object key name, you can set the variable name only in the object text instead of setting the key and value at the same time. JavaScript automatically sets the key name to the variable name and assigns the value to the variable value.
Let firstname = 'Amitav'; let lastname =' Mishra'; / / Longhand let obj = {firstname: firstname, lastname: lastname}; / / Shorthand let obj = {firstname, lastname}
twelve。 Convert string types to numeric types
There are built-in methods, such as parseInt and parseFloat, that can be used to convert strings to numbers. An easier way is to precede the string value with the unary operator (+).
/ / Longhand let total = parseInt ('453'); let average = parseFloat ('42.6'); / / Shorthand let total = + '453'; let average = + '42.6'
13. Repeat the same string multiple times
To repeat a string a specified number of times, you can use a for loop. But you can do it on one line using the repeat () method.
/ / Longhand let str =''; for (let I = 0; I
< 5; i ++) { str += 'Hello '; } console.log(str); // Hello Hello Hello Hello Hello // Shorthand 'Hello '.repeat(5) 小贴士:想通过给某人发100次"对不起"进行道歉?试试repeat()方法。如果你想在每次重复时另起一行,只需加上\n。 14. 指数幂 我们可以用Math.pow()方法求幂。然而用双星号(**)有一个更短的语法。 //Longhand const power = Math.pow(4, 3); // 64 // Shorthand const power = 4**3; // 64 15. 按位双非运算符 按位双非运算符可以替代Math.floor()方法。 //Longhand const floor = Math.floor(6.8); // 6 // Shorthand const floor = ~~6.8; // 6 按位双非运算符方法仅适用于32位整数,即(2**31)-1 = 2147483647。所以对于任何高于2147483647的数字,按位运算符(~~)都会给出错误的结果,所以在这种情况下建议使用Math.floor()。 16. 找出数组的最大值和最小值 可以使用for循环遍历数组的每个值,从而找到最大值或最小值。也可以使用Array.reduce()方法来查找数组中的最大值和最小值。 但是使用扩展运算符则可在一行中完成。 // Shorthand const arr = [2, 8, 15, 4]; Math.max(...arr); // 15 Math.min(...arr); // 2 17. For循环 为遍历数组,通常使用的是传统的for 循环,也可以使用for...of 循环进行遍历。如需访问每个值的索引,可以使用for...in循环。 let arr = [10, 20, 30, 40]; //Longhand for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } //Shorthand //for of loop for (const val of arr) { console.log(val); } //for in loop for (const index in arr) { console.log(arr[index]); } 使用for...in循环还可以遍历对象属性。 let obj = {x: 20, y: 50}; for (const key in obj) { console.log(obj[key]); } 18. 数组合并 let arr1 = [20, 30]; //Longhand let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80] //Shorthand let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80] 19. 多级对象的深度克隆 要深度克隆多级对象,可以遍历每个属性,并检查当前属性是否包含对象。如果是,则通过传递当前属性值(即嵌套对象)对同一函数进行递归调用。也可以使用JSON.stringify()和JSON.parse()在一行中实现。 let obj = {x: 20, y: {z: 30}}; //Longhand const makeDeepClone = (obj) =>{let newObject = {}; Object.keys (obj) .map (key = > {if (typeof obj [key] = 'object') {newObject [key] = makeDeepClone (obj [key]);} else {newObject [key] = obj [key];}}); return newObject;} const cloneObj = makeDeepClone (obj); / / Shorthand const cloneObj = JSON.parse (JSON.stringify (obj))
If the object property takes a function as its value, the shorthand technique (JSON.parse (JSON.stringify (obj) has no effect. Because when JSON.stringif acts on an object, properties that take functions as values are removed from the object. Therefore, in this case, it is still necessary to use the ordinary method of writing.
20. Get characters from a string
Let str = 'jscurious.com'; / / Longhand str.charAt (2); / / c / / Shorthand str [2]; / / c have you mastered JavaScript shorthand skills after reading the above? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.