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 20 common abbreviation techniques for JavaScript?

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

Share

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

This article introduces 20 commonly used JavaScript abbreviation skills, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The shorthand skills of any programming language can help you write more concise code, allowing you to achieve your goals with less code.

1. Declare variable

/ / Longhand let x; let y = 20; / / Shorthand let x, y = 20

two。 Assign values to multiple variables

We can use array deconstruction to assign values to multiple variables in a row.

/ / Longhand let a, b, c; a = 5; b = 8; c = 12; / / Shorthand let [a, b, c] = [5,8,12]

3. Ternary operator

We can use the ternary (conditional) operator to save five lines of code here.

/ / Longhand let marks = 26; let result; if (marks > = 30) {result = 'Pass';} else {result =' Fail';} / / Shorthand let result = marks > = 30? 'Pass': 'Fail'

4. Assign default value

We can use the OR (| |) short circuit operation to assign a default value to a variable if the expected value is incorrect.

/ / 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 operation

If you only call a function when a variable is true, you can write with a short circuit with (& &).

/ / Longhand if (isLoggedin) {goToHomepage ();} / Shorthand isLoggedin & & goToHomepage ()

This is useful with (& &) short-circuit writing when you want to conditionally render a component in React. For example:

{this.state.isLoading & &}

6. Swap two variables

To exchange two variables, we usually use the third variable. We can use array deconstruction assignments to exchange two variables.

Let x = 'Hello', y = 55; / / Longhand const temp = x; x = y; y = temp; / / Shorthand [x, y] = [y, x]

7. Arrowhead function

/ / Longhand function add (num1, num2) {return num1 + num2;} / / Shorthand const add = (num1, num2) = > num1 + num2

Reference: JavaScript Arrow function

Https://jscurious.com/javascript-arrow-function/

8. Template string

We usually use the + operator to concatenate string variables. Using ES6's template string, we can do this in a simpler way.

/ / Longhand console.log ('You got a missed call from' + number +'at'+ time); / / Shorthand console.log (`You got a missed call from ${number} at ${time} `)

9. Multiline string

For multiline strings, we typically use the + operator and a new line escape character (\ n). We can use (`) to implement it in a simpler way.

/ / Longhand console.log ('JavaScript, often abbreviated as JS, is a\ n' +' programming language that conforms 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 language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi- paradigm.`)

10. Multi-condition check

For multiple value matches, we can put all the values in an array and then 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 copy

If the variable name is the same as the property name of the object, then we only need to declare the variable name in the object statement instead of declaring both the key and the value. JavaScript automatically uses the key as the name of the variable and the value as the value of the variable.

Let firstname = 'Amitav'; let lastname =' Mishra'; / / Longhand let obj = {firstname: firstname, lastname: lastname}; / / Shorthand let obj = {firstname, lastname}

twelve。 Convert strings to numbers

There are built-in methods, such as parseInt and parseFloat, that can be used to convert strings to numbers. We can also do this simply by providing a unary operator (+) before the string.

/ / Longhand let total = parseInt ('453'); let average = parseFloat ('42.6'); / / Shorthand let total = + '453'; let average = + '42.6'

13. To repeat a string multiple times to repeat a string N times, you can use a for loop. But with the repeat () method, we can do it with one line of code.

/ / 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 遍"sorry"来道歉吗?用 repeat() 方法试试吧。如果你想要每次在新的一行重复字符串,可以在字符串后面加一个 \n 。 'sorry\n'.repeat(100); 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 来自 Caleb 的评论的改进: 双非位运算符只对 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]); } 参考:JavaScript 中遍历对象和数组的不同方法 https://jscurious.com/different-ways-to-iterate-through-objects-and-arrays-in-javascript/ 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(),如果我们的对象不包含函数、undefined、NaN 或日期值的话。 如果有一个单级对象,例如没有嵌套的对象,那么我们也可以使用扩展符来实现深拷贝。 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)) / / Shorthand for single level object let obj = {x: 20, y: 'hello'}; const cloneObj = {... obj}

Improvements from comments: if your object contains function, undefined or NaN values, JSON.parse (JSON.stringify (obj)) will not be valid. Because when you JSON.stringify an object, the property that contains the function, undefined or NaN value will be removed from the object. Therefore, you can use JSON.parse (JSON.stringify (obj)) when your object contains only string and numeric values.

Reference: JSON.parse () and JSON.stringify ()

Https://jscurious.com/difference-between-json-parse-and-json-stringify/

20. Get the characters in the string

Let str = 'jscurious.com'; / / Longhand str.charAt (2); / / c / / Shorthand str [2]; / / c this is the end of the 20 commonly used JavaScript abbreviation techniques. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

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