App下載

5個小技巧讓你寫出更好的JavaScript

猿友 2020-09-09 14:23:28 瀏覽數(shù) (2092)
反饋

文章來源于公眾號:前端人

在使用 JavaScript 時,我們常常要寫不少的條件語句。這里有五個小技巧,可以讓你寫出更干凈、漂亮的條件語句。

使用 Array.includes 來處理多重條件

舉個栗子 :

// 條件語句
function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');
  }
}

乍一看,這么寫似乎沒什么大問題。

然而,如果我們想要匹配更多的紅色水果呢,比方說『櫻桃』和『蔓越莓』?我們是不是得用更多的 || 來擴(kuò)展這條語句?

我們可以使用 Array.includes重寫以上條件句。

function test(fruit) {
  // 把條件提取到數(shù)組中
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}

我們把紅色的水果(條件)都提取到一個數(shù)組中,這使得我們的代碼看起來更加整潔。

少寫嵌套,盡早返回

讓我們?yōu)橹暗睦犹砑觾蓚€條件:

如果沒有提供水果,拋出錯誤;

如果該水果的數(shù)量大于 10,將其打印出來。

function test(fruit, quantity) {
    const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
    // 條件 1:fruit 必須有值
    if (fruit) {
        // 條件 2:必須為紅色
        if (redFruits.includes(fruit)) {
          console.log('red');
          // 條件 3:必須是大量存在
          if (quantity > 10) {
            console.log('big quantity');
          }
        }
    } else {
        thrownewError('No fruit!');
    }
}


// 測試結(jié)果
test(null); // 報錯:No fruits


test('apple'); // 打?。簉ed


test('apple', 20); // 打印:red,big quantity

讓我們來仔細(xì)看看上面的代碼,我們有:

1 個 if/else 語句來篩選無效的條件;

3 層if語句嵌套(條件 1,2 & 3)。

就我個人而言,我遵循的一個總的規(guī)則是當(dāng)發(fā)現(xiàn)無效條件時盡早返回。

/ 當(dāng)發(fā)現(xiàn)無效條件時盡早返回 /

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  // 條件 1:盡早拋出錯誤
  if (!fruit) thrownewError('No fruit!');
  // 條件2:必須為紅色
  if (redFruits.includes(fruit)) {
    console.log('red');
    // 條件 3:必須是大量存在
    if (quantity > 10) {
      console.log('big quantity');
    }
  }
}

如此一來,我們就少寫了一層嵌套。這是種很好的代碼風(fēng)格,尤其是在 if 語句很長的時候(試想一下,你得滾動到底部才能知道那兒還有個 else 語句,是不是有點不爽)。

如果反轉(zhuǎn)一下條件,我們還可以進(jìn)一步地減少嵌套層級。注意觀察下面的條件 2 語句,看看是如何做到這點的:

/ 當(dāng)發(fā)現(xiàn)無效條件時盡早返回 /

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  if (!fruit) thrownewError('No fruit!'); // 條件 1:盡早拋出錯誤
  if (!redFruits.includes(fruit)) return; // 條件 2:當(dāng) fruit 不是紅色的時候,直接返回
  console.log('red');
  // 條件 3:必須是大量存在
  if (quantity > 10) {
    console.log('big quantity');
  }
}

通過反轉(zhuǎn)條件 2 的條件,現(xiàn)在我們的代碼已經(jīng)沒有嵌套了。

當(dāng)我們代碼的邏輯鏈很長,并且希望當(dāng)某個條件不滿足時不再執(zhí)行之后流程時,這個技巧會很好用。

然而,并沒有任何硬性規(guī)則要求你這么做。這取決于你自己,對你而言,這個版本的代碼(沒有嵌套)是否要比之前那個版本(條件 2 有嵌套)的更好、可讀性更強(qiáng)?

是我的話,我會選擇前一個版本(條件 2 有嵌套)。原因在于:

這樣的代碼比較簡短和直白,一個嵌套的 if 使得結(jié)構(gòu)更加清晰;

條件反轉(zhuǎn)會導(dǎo)致更多的思考過程(增加認(rèn)知負(fù)擔(dān))。

因此,始終追求更少的嵌套,更早地返回,但是不要過度。

使用函數(shù)默認(rèn)參數(shù)和解構(gòu)

我猜你也許很熟悉以下的代碼,在 JavaScript 中我們經(jīng)常需要檢查 null / undefined并賦予默認(rèn)值:

function test(fruit, quantity) {
  if (!fruit) return;
  const q = quantity || 1; // 如果沒有提供 quantity,默認(rèn)為 1
  console.log(`We have ${q}${fruit}!`);
}


//測試結(jié)果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!

事實上,我們可以通過函數(shù)的默認(rèn)參數(shù)來去掉變量 q。

function test(fruit, quantity = 1) { // 如果沒有提供 quantity,默認(rèn)為 1
    if (!fruit) return;
    console.log(`We have ${quantity}${fruit}!`);
}


//測試結(jié)果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!

是不是更加簡單、直白了?

請注意,所有的函數(shù)參數(shù)都可以有其默認(rèn)值。舉例來說,我們同樣可以為 fruit 賦予一個默認(rèn)值:

function test(fruit = ‘unknown’, quantity = 1)。

那么如果 fruit 是一個對象(Object)呢?我們還可以使用默認(rèn)參數(shù)嗎?

function test(fruit) {
  // 如果有值,則打印出來
  if (fruit && fruit.name)  {
    console.log (fruit.name);
  } else {
    console.log('unknown');
  }
}


//測試結(jié)果
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

觀察上面的例子,當(dāng)水果名稱屬性存在時,我們希望將其打印出來,否則打印『unknown』。

我們可以通過默認(rèn)參數(shù)和解構(gòu)賦值的方法來避免寫出 fruit && fruit.name 這種條件。

// 解構(gòu) —— 只得到 name 屬性

// 默認(rèn)參數(shù)為空對象 {}

function test({name} = {}) {
 console.log (name || 'unknown');
}
//測試結(jié)果
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

既然我們只需要 fruitname 屬性,我們可以使用 {name}來將其解構(gòu)出來,之后我們就可以在代碼中使用 name 變量來取代 fruit.name。

我們還使用 {} 作為其默認(rèn)值。

如果我們不這么做的話,

在執(zhí)行 test(undefined) 時,你會得到一個錯誤 Cannot destructure property name of ‘undefined’ or ‘null’.,

因為 undefined 上并沒有 name 屬性。

(譯者注:這里不太準(zhǔn)確,其實因為解構(gòu)只適用于對象(Object),而不是因為undefined 上并沒有 name 屬性(空對象上也沒有)。參考解構(gòu)賦值 - MDN)

如果你不介意使用第三方庫的話,有一些方法可以幫助減少空值(null)檢查:

使用 Lodash get 函數(shù);

使用 Facebook 開源的 idx 庫(需搭配 Babeljs)。

這里有一個使用 Lodash 的例子:

// 使用 lodash 庫提供的 _ 方法

function test(fruit) {
   // 獲取屬性 name 的值,如果沒有,設(shè)為默認(rèn)值 unknown
  console.log(_.get(fruit, 'name', 'unknown');
}
//測試結(jié)果
test(undefined); // unknown


test({ }); // unknown


test({ name: 'apple', color: 'red' }); // apple

你可以在這里運(yùn)行演示代碼。

另外,如果你偏愛函數(shù)式編程(FP),你可以選擇使用 Lodash fp——函數(shù)式版本的 Lodash(方法名變?yōu)?get 或 getOr)。

相較于 switch,Map / Object 也許是更好的選擇

讓我們看下面的例子,我們想要根據(jù)顏色打印出各種水果:

function test(color) {
  // 使用 switch case 來找到對應(yīng)顏色的水果
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}

//測試結(jié)果

test(null); // []

test('yellow'); // ['banana', 'pineapple']

上面的代碼看上去并沒有錯,但是就我個人而言,它看上去很冗長。同樣的結(jié)果可以通過對象字面量來實現(xiàn),語法也更加簡潔:

// 使用對象字面量來找到對應(yīng)顏色的水果

const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
};


function test(color) {
  return fruitColor[color] || [];
}

或者,你也可以使用 Map 來實現(xiàn)同樣的效果:

// 使用 Map 來找到對應(yīng)顏色的水果

const fruitColor = newMap()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);
function test(color) {
  return fruitColor.get(color) || [];
}

Map 是 ES2015 引入的新的對象類型,允許你存放鍵值對。

那是不是說我們應(yīng)該禁止使用 switch 語句?別把自己限制住。

我自己會在任何可能的時候使用對象字面量,但是這并不是說我就不用 switch,這得視場景而定。

就以上的例子,事實上我們可以通過重構(gòu)我們的代碼,使用 Array.filter 實現(xiàn)同樣的效果。

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'strawberry', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'pineapple', color: 'yellow' },
    { name: 'grape', color: 'purple' },
    { name: 'plum', color: 'purple' }
];


function test(color) {
  // 使用 Array filter 來找到對應(yīng)顏色的水果
  return fruits.filter(f => f.color == color);
}

解決問題的方法永遠(yuǎn)不只一種。對于這個例子我們展示了四種實現(xiàn)方法。

Coding is fun!

使用 Array.every 和 Array.some 來處理全部/部分滿足條件

最后一個小技巧更多地是關(guān)于使用新的(也不是很新了)JavaScript 數(shù)組函數(shù)來減少代碼行數(shù)。

觀察以下的代碼,我們想要檢查是否所有的水果都是紅色的:

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];
function test() {
  let isAllRed = true;
  // 條件:所有的水果都必須是紅色
  for (let f of fruits) {
    if (!isAllRed) break;
    isAllRed = (f.color == 'red');
  }
  console.log(isAllRed); // false
}

這段代碼也太長了!我們可以通過 Array.every 來縮減代碼

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];
function test() {
  // 條件:(簡短形式)所有的水果都必須是紅色
  const isAllRed = fruits.every(f => f.color == 'red');
  console.log(isAllRed); // false
}

清晰多了對吧?

類似的,如果我們想要檢查是否有至少一個水果是紅色的,我們可以使用 Array.some 僅用一行代碼就實現(xiàn)出來。

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
];
function test() {
  // 條件:至少一個水果是紅色的
  const isAnyRed = fruits.some(f => f.color == 'red');
  console.log(isAnyRed); // true
}

讓我們一起寫出可讀性更高的代碼吧。希望這篇文章能給你們帶來一些幫助。就是這樣啦~

以上就是W3Cschool編程獅關(guān)于5個小技巧讓你寫出更好的JavaScript的相關(guān)介紹了,希望對大家有所幫助。

0 人點贊