19 commonly used JavaScript shorthand method

Original: https://segmentfault.com/a/1190000012673854

 

1, ternary operator

When the write  IF ... the else  when the statement, instead of using the ternary operator.

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

 Shorthand:

const answer = x>10 ? 'is greater' : 'is lesser';

 Can also be nested if statements:

const big = x>10 ? 'greager 10' : x

 

2, a shorthand way of short-circuit evaluation

When another value assigned to a variable, to determine the original value is not null, undefined or a null value. You can write a multiple condition of the if statement.

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

 Or you may use short-circuit evaluation method:

const variable2 = variable1 || 'new';

 

3, a shorthand method of declaring variables

let x;
let y;
let z = 3;

 Shorthand method:

let x, y, z=3;

 

4, if the conditions exist shorthand method

if(likeJavaScript === true)

 Shorthand:

if(likeJavaScript)

 Only likeJavaScript true value, both statements are equal.

If the value is not a true value is determined, it can be:

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

 Shorthand:

let a;
if( !a ) {
  // do something...  
}

 

5, JavaScript cycle shorthand method

for(let i=0; i<allImgs.length; i++) 

 Shorthand:  for (the let index in allImgs)   can also be used 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] = 9;

 

6, short-circuit evaluation

To the value of a variable is assigned by determining whether the value is null or undefined, it can be:

let dbHost;
if(process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;      
} else {
  dbHost = 'localhost';  
}

 

7, decimal index

When it is desired to write a lot of numbers with zero (e.g. 10000000), may be employed index (1E7) instead of the figure.

 for(let i=0; i<10000; i++){} 简写:

for (the let I = 0; I <10000; I ++ ) {}
 // The following are returned to true 
1E0 ===. 1 ;
 1E1 === 10 ;
 1E2 === 100 ;
 1E3 === 1000 ;
 1E4 === 10000 ;
 1E5 === 100000;

 

8, object properties shorthand

If the attribute name and the name of the same key, the method may be employed for ES6:

const obj = {x: x, y: y};

 Shorthand:

const obj = { x, y }

 

9, arrows abbreviated function

The traditional method is very easy to write a function to understand and write, but when nested within another function, these advantages will be gone.

function sayHello(name) {
  console.log('Hello', name);  
}

setTimeout(function(){
  console.log('Loaded');  
}, 2000);

list.forEach(function(item) {
  console.log(item);  
});

 Shorthand:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

 

10, the implicit return value shorthand

Is often used to return the return statement function final result, a single function can be implicitly arrow returns its value ({} function must be omitted for the return keyword is omitted)

Statements to return multiple rows (e.g., object literal expression), you need to use () function to surround the body.

function calcCircumference(diameter) {
  return Math.PI * diameter  
}

var func = function func() {
  return { foo: 1 };  
}

 Shorthand:

calcCircumference = diameter => (
 Math.PI * diameter;   
)

var func = () => ({ foo: 1 });

 

11, default parameter values

In order to pass default values ​​to the parameters of the function, generally use an if statement to write, but using ES6 define default values ​​will be very simple:

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

 Shorthand:

volume = (1, w=3, h=4) => (1*w*h);
volume(2)  // output: 24

 

12, template string

The traditional JavaScript language output templates are usually written like this.

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

 ES6 can Backticks $ {} and abbreviations are used:

const welcome = 'You have logged in as ${first} ${last}';

const db = 'http://${host}:${port}/${database}';

 

13, deconstruction shorthand method of assignment

In the framework of the web, or an array of objects often need to pass data from the literal form back and forth between the component and the API, then you 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;

 Shorthand:

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

 You can also assign variable names:

Store {const, form, loading, errors, Entity: contact} = the this .props;
 // last contact a variable named

 

14, multi-line strings shorthand

It requires multi-line output strings need to splice +:

Cost = lorem 'lorem ipsum carrots, tomato \ n \ t " 

  +" rebates, but they do eiusood time and vitality \ n \ t " 

  +" to labor and obesity. Over the years \ n \ t " 

  +" I, who nostrud work, exercise, school district \ n \ t " 

  +" except for the convenience of aliquip consequat.Duis if \ n \ t " 

  +" cupidatat consumer to find a pleasure that . \ n \ t '

 Use of anti-quotation marks, you can reach the abbreviated role:

const = lorem  
lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod, and long-and vitality, so that the labor of the pain of obesity. Over the years, I will come, who will nostrud aliquip out of her the advantage of exercise, so that stimulus efforts if the school district and longevity. But consumer cupidatat homework to find the pleasure wants to be. "

 

15, extended operator shorthand

Extended operator has examples of use make more efficient use of JavaScript code, may 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()

 Shorthand:

// 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 concat () function, you can use the extended operator to another array inserted anywhere in an array.

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

 Operators can also use the extended deconstruction:

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, mandatory parameter shorthand

JavaScript If not, the parameters passed to the function parameter value is undefined. In order to enhance the parameter assignment, you can use the if statement to throw an exception, or the use of mandatory parameter shorthand method.

function foo(bar) {
  if(bar === undifined) {
    throw new Error('Missing parameter!');    
  }  
  return bar;  
}

 Shorthand:

mandatory = () => {
  throw new Error('Missing parameter!');  
}

foo = (bar = mandatory()) => {
  return bar;  
}

  

17, Array.find shorthand

Want to find a value from an array, you need to cycle. In the ES6, find () function to 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<pets.length; i++) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }  
}

 Shorthand:

pet = pets.find(pet => pet.type === 'Dog' && pet.name === 'Tommy');
console.log(pet); //{ type:'Dog', name:'Tommy' }

 18, Object [key] shorthand

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

 When you need to assume different domains and validation rules, the ability to write a generic function to confirm at runtime?

// object verification rules 
const Schema = { 
  First: { 
    required: to true 
  }, 
  Last: { 
    required: to true 
  }   
} 

// generic verification function 
const = the validate (Schema, values) => {
   for (Field in Schema) {
     IF ( Schema [Field] .required) {
       IF (! values [Field]) {
         return  to false ; 
      } 
    } 
  } 
  return  to true ;   
} 

the console.log (the validate (Schema, {First: 'Bruce'})); //falsle
console.log(validate(schema, {first:'Bruce', last:'Wayne'})); //true

 There is now applicable in all situations validation function is not required for each written a custom validation function

 

19, non-dual bit operation shorthand

Embodiment has an effective use of a dual non-arithmetic operators. Can be used instead Math.floor (), its advantage is to run faster.

Math.floor(4.9) === 4 //true

 Shorthand:

~~4.9 === 4  //true

 

Guess you like

Origin www.cnblogs.com/liangchen2250/p/10990390.html