19 個 JavaScript 編碼小技巧

大漠發表於2017-06-23

這篇文章適合任何一位基於JavaScript開發的開發者。我寫這篇文章主要涉及JavaScript中一些簡寫的程式碼,幫助大家更好理解一些JavaScript的基礎。希望這些程式碼能從不同的角度幫助你更好的理解JavaScript。

三元操作符

如果使用if...else語句,那麼這是一個很好節省程式碼的方式。

Longhand:

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

Shorthand:

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:

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

宣告變數

在函式中宣告變數時,像下面這樣同時宣告多個變數可以節省你大量的時間和空間:

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

推薦一個嗎?

我真的喜歡這些小技巧,希望能有更多關於這方面的JavaScript小技巧。如果你有這方面的,歡迎在下面的評論中與我們一起分享。

相關文章