JavaScript shorthand skills

This article comes from years of experience JavaScript coding techniques, suitable for all developers are using JavaScript programming read.

The purpose of this article is to help you more skilled use of JavaScript language to carry out development work.

The article is divided into primary articles and advanced part of two parts, were introduced.

Primary articles
1, ternary operator
following is a good example, if a full statement, abbreviated line of code.

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

Abbreviated as:

const answer = x > 10 ? 'greater than 10' : 'less than 10';

2, loop
when using pure JavaScript (not rely on external libraries, such as jQuery or lodash), the following abbreviations will be useful.

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

Abbreviated as:

for (let index of allImgs)

The following is a short example of forEach iterate:

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

3, declare variables
before the start of the function, the variable assignment is a good habit. When declare multiple variables:

let x;
let y;
let z = 3;

It can be abbreviated as:

let x, y, z=3;

. 4, if statement
in use is determined if basic, the assignment operator can be omitted.

if (likeJavaScript === true)

Abbreviated as:

if (likeJavaScript)

5, decimal number
may be used instead of a large scientific notation data, such as 10 million may be abbreviated as 1e7.

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

Abbreviated as:

for (let i = 0; i < 1e7; i++) { }

6, multi-line strings
If you need to write multiple lines of code in a string, like this:

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'
但是还有一个更简单的方法,只使用引号:

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.`

            web前端开发资源Q-q-u-n: 767273102 ,内有免费开发工具,零基础,进阶视频教程,希望新手少走弯路

Advanced articles

1, variable assignment
when the value of one variable to another variable, you first need to make sure that the original value is not null, undefined or null.

It may be determined by writing a sentence including a plurality of conditions:

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

Or abbreviated in the following forms:

const variable2 = variable1  || 'new';

The following code can be pasted into es6console in their own test:

let variable1;
let variable2 = variable1  || '';
console.log(variable2 === ''); // prints true
variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints foo

2, the default value assignment

If the expected parameter is null or undefined, you do not need to write six lines of code to assign default values. We can use only a short logical operator, with one line of code to accomplish the same operation.

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

Abbreviated as:

const dbHost = process.env.DB_HOST || 'localhost';

3, object properties

ES6 provides a very simple way to assign object properties. If the attribute name and the name of the same key, you can use shorthand.

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

Abbreviated as:

const obj = { x, y };

4, arrows function

Classic function it is easy to read and write, but if the nest when they call in other functions, the entire function will become lengthy and somewhat confusing. This time you can use arrow function shorthand:

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

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

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

Abbreviated as:

sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));

5, the return value of the implicit

The return value is a function we normally used to return the final results of the keyword. A statement is only a function of the arrows, implicitly return result (function must be omitted braces ({}), in order to return the keyword is omitted).

To return to the multi statements (e.g. text objects), required () {} instead of the function to wrap the body. This ensures that the code be evaluated in the form of individual statements.

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

Abbreviated as:

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

6, the default parameter values

You can use an if statement to define default values ​​of function arguments. ES6 specified in the default values ​​can be defined in the function declaration.

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

Abbreviated as:

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

7, template string

In the past we used to use the "+" to convert multiple variables to strings, but there is no easier way to do that?

ES6 provided a corresponding method, we can use the inverse quotes and $ {variable} into one string.

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

Abbreviated as:

const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;

8, deconstruction assignment

Destructuring assignment is an expression, a variable property value for rapid extraction from the array or object, and assigns defined.

In the code shorthand terms, deconstruction assignment can achieve very good results.

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;

Abbreviated as:

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

You can even specify your own variable names:

const { store, form, loading, errors, entity:contact } = this.props;

9, the operator Expand

Expand operator is introduced in ES6 using expand the operator can make JavaScript code more effective and fun.

Using Expand operator to replace some of the array functions.

// 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( )

Abbreviated as:

// 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];

And concat () function is different, a user can use the extended operators into another array in any array.

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

May be used to expand and ES6 operator binding deconstruction symbols:

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 }

10, mandatory parameters

By default, if you do not, then the JavaScript function will set the parameters passed to the function parameter value is undefined. Other languages ​​will be issued a warning or error. To perform parameter assignment, you can use an if statement throws an undefined error, or you can use the "mandatory parameter."

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

Abbreviated as:

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

11、Array.find

If you ever written in JavaScript find common functions, then you might use a for loop. In ES6, the array introduces a new function called find () may be achieved for short loop.

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];
    }
  }
}

12、Object [key]

Although foo.bar written foo [ 'bar'] is a common practice, but this approach forms the basis for the preparation of reusable code.

Consider the following simplified example of this verification function:

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

The above function perfectly complete the verification work. But when there are many forms, you'll need to verify the application, this time there will be different fields and rules. If you can build a common configuration validation functions at runtime, it would be a good choice.

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].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, with this verification function, we can reuse in all forms without having to write custom validation function for each form. web front-end development resources Qqun: 767273102, there are free development tools, zero-based, advanced video tutorials, I hope the novice detours

13, two-position operator

Bitwise Operators are the basic knowledge of JavaScript primary curriculum, but we do not often use bit operators. Because in the case does not deal with binary, no one wants to use the 1 and 0.

But there is a two-bit operator very practical case. You can use the two-position operator to replace Math.floor (). Advantages bit double negation operator in that it performs the same operation faster.

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

Abbreviated as:

~~4.9 === 4  //true

JavaScript development tool recommended

SpreadJS distal pure form is based on the control grid and spreadsheet JavaScript functionality controls HTML5 provide a complete formula engine, sorting, filtering, input control, data visualization, Excel import / export functions for .NET, Java and mobile end platforms such as online editing functions like Excel spreadsheet program development.

Above are some commonly used JavaScript shorthand skills, if there are other shorthand skills not mentioned, but also welcome to add.

Guess you like

Origin blog.51cto.com/14436164/2418619