1. 程式人生 > 實用技巧 >JS超有用的簡寫技巧

JS超有用的簡寫技巧

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

2.短路求值簡寫方式

當給一個變數分配另一個值時,想確定源始值不是null,undefined或空值。可以寫撰寫一個多重條件的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)

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.預設引數值

為了給函式中引數傳遞預設值,通常使用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  

  

7.解構賦值簡寫方法

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   後面的contact才是const的變數明

  

8.擴充套件運算子簡寫

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

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 }

  

9.強制引數簡寫

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

  

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

  

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

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

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 

  

12.雙重非位運算簡寫

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

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

簡寫:~~4.9 === 4 //true