19 个 JavaScript 编码小技巧

这篇文章适合任何一位基于JavaScript开发的开发者。我写这篇文章主要涉及JavaScript中一些简写的代码,帮助你们更好理解一些JavaScript的基础。但愿这些代码能从不一样的角度帮助你更好的理解JavaScript。javascript

三元操做符

若是使用if...else语句,那么这是一个很好节省代码的方式。vue

Longhand:java

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

Shorthand:es6

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

你还能够像下面这样嵌套if语句:数组

const big = x > 10 ? " greater 10" : x

Short-circuit Evaluation

分配一个变量值到另外一个变量的时候,你可能想要确保变量不是nullundefined或空。你能够写一个有多个if的条件语句或者Short-circuit Evaluation。框架

Longhand:less

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

Shorthand:函数

const variable2 = variable1  || 'new';

不要相信我,请先相信本身的测试(能够把下面的代码粘贴在es6console)测试

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

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

声明变量

在函数中声明变量时,像下面这样同时声明多个变量能够节省你大量的时间和空间:ui

Longhand:

let x;
let y;
let x = 3;

Shorthand:

let x, y, z=3;

若是存在

这多是微不足道的,但值得说起。作“若是检查”时,赋值操做符有时能够省略。

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

注:这两种方法并不彻底相同,简写检查只要likeJavaScripttrue都将经过。

这有另外一个示例。若是a不是true,而后作什么。

Longhand:

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

Shorthand:

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

JavaScript的for循环

若是你只想要原生的JavaScript,而不想依赖于jQuery或Lodash这样的外部库,那这个小技巧是很是有用的。

Longhand:

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

Shorthand:

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] = 9

Short-circuit Evaluation

若是参数是null或者是undefined,咱们能够简单的使用一个Short-circuit逻辑运算,实现一行代码替代六行代码的写法。

Longhand:

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

Shorthand:

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

十进制指数

你可能看过这个。它本质上是一个写数字的奇特写法,就是一个数字后面有不少个0。例如1e7本质至关于100000001的后面有70)。它表明了十进制计数等于10000000

Longhand:

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

Shorthand:

for (let i = 0; i < 1e7; i++) {}
// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

对象属性

定义对象文字(Object literals)让JavaScript变得更有趣。ES6提供了一个更简单的办法来分配对象的属性。若是属性名和值同样,你可使用下面简写的方式。

Longhand:

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

Shorthand:

const obj = { x, y };

箭头函数

经典函数很容易读和写,但它们确实会变得有点冗长,特别是嵌套函数中调用其余函数时还会让你感到困惑。

Longhand:

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));

隐式返回

return在函数中常用到的一个关键词,将返回函数的最终结果。箭头函数用一个语句将隐式的返回结果(函数必须省略{},为了省略return关键词)。

若是返回一个多行语句(好比对象),有必要在函数体内使用()替代{}。这样能够确保代码是否做为一个单独的语句返回。

Longhand:

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

Shorthand:

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

默认参数值

你可使用if语句来定义函数参数的默认值。在ES6中,能够在函数声明中定义默认值。

Longhand:

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

Shorthand:

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

Template Literals

是否是厌倦了使用+来链接多个变量变成一个字符串?难道就没有一个更容易的方法吗?若是你能使用ES6,那么你是幸运的。在ES6中,你要作的是使用撇号和${},而且把你的变量放在大括号内。

Longhand:

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

Shorthand:

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

Destructuring Assignment

若是你正在使用任何一个流行的Web框架时,就有不少机会使用数组的形式或数据对象的形式与API之间传递信息。一旦数据对象达到一个对个组件时,你须要将其展开。

Longhand:

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;

你甚至能够本身指定变量名:

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

多行字符串

你会发现之前本身写多行字符串的代码会像下面这样:

Longhand:

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'

但还有一个更简单的方法。使用撇号。

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

Spread Operator

Spread Operator是ES6中引入的,使JavaScript代码更高效和有趣。它能够用来代替某些数组的功能。Spread Operator只是一个系列的三个点(...)。

Longhand:

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

不像concat()函数,使用Spread Operator你能够将一个数组插入到另外一个数组的任何地方。

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

另外还能够看成解构符:

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 }

强制参数

默认状况下,JavaScript若是不给函数参数传一个值的话,将会是一个undefined。有些语言也将抛出一个警告或错误。在执行参数赋值时,你可使用if语句,若是未定义将会抛出一个错误,或者你可使用强制参数(Mandatory parameter)。

Longhand:

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

Shorthand:

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

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

Array.find

若是你之前写过一个查找函数,你可能会使用一个for循环。在ES6中,你可使用数组的一个新功能find()

Longhand:

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' }

Object[key]

你知道Foo.bar也能够写成Foo[bar]吧。起初,彷佛没有理由应该这样写。然而,这个符号可让你编写可重用代码块。

下面是一段简化后的函数的例子:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

这个函数能够正常工做。然而,须要考虑一个这样的场景:有不少种形式须要应用验证,并且不一样领域有不一样规则。在运行时很难建立一个通用的验证功能。

Shorthand:

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

如今咱们有一个验证函数,能够各类形式的重用,而不须要为每一个不一样的功能定制一个验证函数。

Double Bitwise NOT

若是你是一位JavaScript新手的话,对于逐位运算符(Bitwise Operator)你应该永远不会在任何地方使用。此外,若是你不处理二进制01,那就更不会想使用。

然而,一个很是实用的用例,那就是双位操做符。你能够用它替代Math.floor()。Double Bitwise NOT运算符有很大的优点,它执行相同的操做要快得多。你能够在这里阅读更多关于位运算符相关的知识。

Longhand:

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

Shorthand:

~~4.9 === 4  //true

来源: VUE中文社区

相关文章
相关标签/搜索