19 個 JavaScript 常用的簡寫技術

yuyurenjie發表於2017-06-22

原文連結,最近很火的一篇文章

1.三元操作符

當想寫if...else語句時,使用三元操作符來代替。

const x = 20;
let answer;
if (x > 10) {
    answer = 'is greater';
} else {
    answer = 'is lesser';
}複製程式碼

簡寫:

const answer = x > 10 ? 'is greater' : 'is lesser';複製程式碼

也可以巢狀if語句:

const big = x > 10 ? " greater 10" : x複製程式碼

2.短路求值簡寫方式

當給一個變數分配另一個值時,想確定源始值不是nullundefined或空值。可以寫撰寫一個多重條件的if語句。

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}複製程式碼

或者可以使用短路求值方法:

const variable2 = variable1  || 'new';複製程式碼

3.宣告變數簡寫方法

let x;
let y;
let z = 3;複製程式碼

簡寫方法:

let x, y, z=3;複製程式碼

4.if存在條件簡寫方法

if (likeJavaScript === true)複製程式碼

簡寫:

if (likeJavaScript)複製程式碼

只有likeJavaScript是真值時,二者語句才相等

如果判斷值不是真值,則可以這樣:

let a;
if ( a !== true ) {
// do something...
}複製程式碼

簡寫:

let a;
if ( !a ) {
// do something...
}複製程式碼

5.JavaScript迴圈簡寫方法

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] = 9複製程式碼

6.短路評價

給一個變數分配的值是通過判斷其值是否為nullundefined,則可以:

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.隱式返回值簡寫

經常使用return語句來返回函式最終結果,一個單獨語句的箭頭函式能隱式返回其值(函式必須省略{}為了省略return關鍵字)

為返回多行語句(例如物件字面表示式),則需要使用()包圍函式體。

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

var func = function func() {
  return { foo: 1 };
};複製程式碼

簡寫:

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

var func = () => ({ foo: 1 });複製程式碼

11.預設引數值

為了給函式中引數傳遞預設值,通常使用if語句來編寫,但是使用ES6定義預設值,則會很簡潔:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}複製程式碼

簡寫:

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) //output: 24複製程式碼

12.模板字串

傳統的JavaScript語言,輸出模板通常是這樣寫的。

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

const db = 'http://' + host + ':' + port + '/' + database;複製程式碼

ES6可以使用反引號和${}簡寫:

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

const db = `http://${host}:${port}/${database}`;複製程式碼

13.解構賦值簡寫方法

在web框架中,經常需要從元件和API之間來回傳遞陣列或物件字面形式的資料,然後需要解構它

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;複製程式碼

簡寫:

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;複製程式碼

也可以分配變數名:

const { store, form, loading, errors, entity:contact } = this.props;
//最後一個變數名為contact複製程式碼

14.多行字串簡寫

需要輸出多行字串,需要使用+來拼接:

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.`複製程式碼

15.擴充套件運算子簡寫

擴充套件運算子有幾種用例讓JavaScript程式碼更加有效使用,可以用來代替某個陣列函式。

// 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()複製程式碼

簡寫:

// 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()函式,可以使用擴充套件運算子來在一個陣列中任意處插入另一個陣列。

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 }複製程式碼

16.強制引數簡寫

JavaScript中如果沒有向函式引數傳遞值,則引數為undefined。為了增強引數賦值,可以使用if語句來丟擲異常,或使用強制引數簡寫方法。

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}複製程式碼

簡寫:

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

foo = (bar = mandatory()) => {
  return bar;
}複製程式碼

17.Array.find簡寫

想從陣列中查詢某個值,則需要迴圈。在ES6中,find()函式能實現同樣效果。

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];
    }
  }
}複製程式碼

簡寫:

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

18.Object[key]簡寫

考慮一個驗證函式

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

console.log(validate({first:'Bruce',last:'Wayne'})); // true複製程式碼

假設當需要不同域和規則來驗證,能否編寫一個通用函式在執行時確認?

// 物件驗證規則
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// 通用驗證函式
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複製程式碼

現在可以有適用於各種情況的驗證函式,不需要為了每個而編寫自定義驗證函式了

19.雙重非位運算簡寫

有一個有效用例用於雙重非運算操作符。可以用來代替Math.floor(),其優勢在於執行更快,可以閱讀此文章瞭解更多位運算。

Math.floor(4.9) === 4  //true複製程式碼

簡寫

~~4.9 === 4  //true複製程式碼

歡迎訂閱掘金專欄知乎專欄

相關文章