19個JavaScript編碼小技巧,值得學習一下!

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

三元操作符

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

Longhand:

const x = 20;

let big;

if (x > 10) {

big = true;

} else {

big = false;

}

Shorthand:

const big = x > 10 ? true : false;

你還可以像下面這樣嵌套if語句:

const big = x > 10 ? 'greater 10' : x < 5 ? 'less 5' : 'between 5 and 10';

Short-circuit Evaluation

分配一個變量值到另一個變量的時候,你可能想要確保變量不是null、undefined或空。你可以寫一個有多個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 === ''); // true

variable1 = 'foo';

variable2 = variable1 || '';

console.log(variable2); // foo

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

Longhand:

let x;

let y;

let x = 3;

Shorthand:

let x, y, z = 3;

如果存在

這可能是微不足道的,但值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: tru


分享到:


相關文章: