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 shorthand skills of JavaScript

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

Share

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

This article mainly explains "what are the shorthand skills of JavaScript". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the shorthand skills of JavaScript"?

1. Ternary operator

When you want to write if...else statements, use ternary operators instead.

Const x = 20; let answer; if (x > 10) {answer ='is greater';} else {answer ='is lesser';}

Abbreviation:

Const answer = x > 10? 'is greater':'is lesser'

You can also nest if statements:

Const big = x > 10? "greater 10": X

two。 Shorthand method of short circuit evaluation

When assigning another value to a variable, you want to make sure that the source value is not null, undefined, or null. You can write an if statement with multiple conditions.

If (variable1! = = null | | variable1! = = undefined | | variable1! ='') {let variable2 = variable1;}

Or you can use the short-circuit evaluation method:

Const variable2 = variable1 | | 'new'

3. Declare variable shorthand method let x; let y; let z = 3

Abbreviation method:

Let x, y, zonal 3

4.if existence condition abbreviation method if (likeJavaScript = = true)

Abbreviation:

If (likeJavaScript)

Only when likeJavaScript is true, the two statements are equal.

If the judgment value is not true, you can do this:

Let a; if (a! = = true) {/ / do something... }

Abbreviation:

Let a; if (! a) {/ / do something... } 5.JavaScript loop abbreviation method for (let I = 0; I

< allImgs.length; i++) 简写: for (let index in allImgs) 也可以使用Array.forEach: function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [2, 5, 9].forEach(logArrayElements); // logs: // a[0] = 2 // a[1] = 5 // a[2] = 96.短路评价 给一个变量分配的值是通过判断其值是否为 null 或undefined ,则可以: let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; } 简写: const dbHost = process.env.DB_HOST || 'localhost'; 7.十进制指数 当需要写数字带有很多零时(如10000000),可以采用指数(1e7)来代替这个数字:for (let i = 0; i < 10000; i++) {}简写: for (let i = 0; i < 1e7; i++) {} // 下面都是返回true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;8.对象属性简写 如果属性名与 key 名相同,则可以采用 ES6 的方法: const obj = { x:x, y:y }; 简写: const obj = { x, y }; 9.箭头函数简写 传统函数编写方法很容易让人理解和编写,但是当嵌套在另一个函数中,则这些优势就荡然无存。 function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); }); 简写: sayHello = name =>

Console.log ('Hello', name); setTimeout () = > console.log (' Loaded'), 2000); list.forEach (item = > console.log (item)); 10. Abbreviation of implicit return value

The return statement is often used to return the final result of a function, and the arrow function of a single statement can implicitly return its value (the function must omit {} in order to omit the return keyword).

To return a multiline statement, such as an object literal expression, you need to surround the function body with ().

Function calcCircumference (diameter) {return Math.PI * diameter} var func = function func () {return {foo: 1};}

Abbreviation:

CalcCircumference = diameter = > (Math.PI * diameter;) var func = () > ({foo: 1}); 11. Default parameter valu

In order to pass default values to parameters in a function, you usually use if statements to write, but using ES6 to define default values is very concise:

Function volume (l, w, h) {if (w = undefined) w = 3; if (h = undefined) h = 4; return l * w * h;}

Abbreviation:

Volume = (l, w = 3, h = 4) = > (l * w * h); volume (2) / / output: 2412. Template string

In the traditional JavaScript language, the output template is usually written like this.

Const welcome = 'You have logged in as' + first +''+ last +'. Const db = 'http://' + host +':'+ port +'/'+ database

ES6 can use backquotes and ${} abbreviations:

Const welcome = `You have logged in as ${first} ${last} `; const db = `http://${host}:${port}/${database}`;13. Deconstructing the abbreviated method of assignment

In the web framework, it is often necessary to pass literal array or object data back and forth between the component and the API, and then need to deconstruct it

Const observable = require ('mobx/observable'); const action = require (' mobx/action'); const runInAction = require ('mobx/runInAction'); const store = this.props.store; const form = this.props.form; const loading = this.props.loading; const errors = this.props.errors; const entity = this.props.entity

Abbreviation:

Import {observable, action, runInAction} from 'mobx'; const {store, form, loading, errors, entity} = this.props

You can also assign a variable name:

Const {store, form, loading, errors, entity:contact} = this.props; / / the last variable is named contact14. Multiline string abbreviation

You need to output multiple lines of strings, and you need to use + to concatenate:

Const lorem = 'Lorem ipsum dolor sit amet, consectetur\ n\ t' + 'adipisicing elit, sed do eiusmod tempor incididunt\ n\ t' +'ut labore et dolore magna aliqua. Ut enim ad minim\ n\ t'+ 'veniam, quis nostrud exercitation ullamco laboris\ n\ t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\ n\ t' + 'irure dolor in reprehenderit in voluptate velit esse.\ n\ t'

Using backquotation marks, you can achieve the effect of shorthand:

Const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.`15. Extension operator abbreviation

The extension operator has several use cases that make JavaScript code more efficient and can be used instead of an array function.

/ / joining arrays const odd = [1,3,5]; const nums = [2,4,6] .concat (odd); / / cloning arrays const arr = [1,2,3,4]; const arr2 = arr.slice ()

Abbreviation:

/ joining arrays const odd = [1, 3, 5]; const nums = [2, 4, 6,... odd]; console.log (nums); / / [2, 4, 6, 1, 3, 5] / / cloning arrays const arr = [1, 2, 3, 4]; const arr2 = [. Arr]

Unlike the concat () function, you can use the extension operator to insert an array anywhere in an array.

Const odd = [1,3,5]; const nums = [2,... odd, 4,6]

You can also use extension operators to deconstruct:

Const {a, b,... z} = {a: 1, b: 2, c: 3, d: 4}; console.log (a) / / 1 console.log (b) / / 2 console.log (z) / / {c: 3, d: 4} 16. Forced parameter abbreviation

If no value is passed to the function parameter in JavaScript, the parameter is undefined. To enhance parameter assignment, you can use the if statement to throw an exception, or use the forced parameter shorthand method.

Function foo (bar) {if (bar = undefined) {throw new Error ('Missing parameterized');} return bar;}

Abbreviation:

Mandatory = () = > {throw new Error ('Missing parameterized');} foo = (bar = mandatory ()) = > {return bar;} 17.Array.find abbreviation

To find a value from an array, you need a loop. In ES6, the find () function can achieve the same effect.

Const pets = [{type: 'Dog', name:' Max'}, {type: 'Cat', name:' Karl'}, {type: 'Dog', name:' Tommy'},] function findDog (name) {for (let I = 0; I pet.type = 'Dog' & & pet.name =' Tommy'); console.log (pet) / / {type: 'Dog', name:' Tommy'} 18.Object [key] abbreviation

Consider a validation function

Function validate (values) {if (! values.first) return false; if (! values.last) return false; return true;} console.log (validate ({first:'Bruce',last:'Wayne'})); / / true

Suppose that when different fields and rules are needed to verify, can you write a general function to confirm at run time?

/ / object validation rules const schema = {first: {required:true}, last: {required:true}} / / General validation function const validate = (schema, values) = > {for (field in schema) {if (schemafield] .required) {if (! values [field]) {return false } return true;} console.log (validate (schema, {first:'Bruce'})); / / false console.log (validate (schema, {first:'Bruce',last:'Wayne'})); / / true

Now you can have validation functions for a variety of situations, and you don't need to write custom validation functions for each

19. Abbreviation of double non-bit operation

There is a valid use case for double non-operational operators. Can be used instead of Math.floor (), which has the advantage of running faster.

Math.floor (4.9) = 4 / / true

Abbreviation:

Thank you for your reading. These are the contents of "what are the abbreviation skills of JavaScript?" after the study of this article, I believe you have a deeper understanding of what the abbreviation skills of JavaScript have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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