1. 程式人生 > 程式設計 >JavaScript簡寫技巧

JavaScript簡寫技巧

目錄
  • 1. 合併陣列
  • 2. 合併陣列(在開頭位置)
  • 3. 克隆陣列
  • 4. 解構賦值
  • 5. 模板字面量
  • 6. For迴圈
  • 7. 箭頭函式
  • 8. 在陣列中查詢物件
  • 9. 將字串轉換為整數
  • 10. 短路求值
  • 補充幾點
    • 箭頭函式
    • 在陣列中查詢物件
    • 短路求值替代方案

1. 合併陣列

普通寫法

我們通常使用Array中的concat()方法合併兩個陣列。用concat()方法來合併兩個或多個數組,不會更改現有的陣列,而是返回一個新的陣列。請看一個簡單的例子:

let apples = ['🍎','🍏'];
let fruits = ['🍉','🍊','🍇'].concat(apples);

console.log( fruits );
//=> ["🍉","🍊","🍇","🍎","🍏"]

簡寫方法

我們可以通過使用ES6擴充套件運算子(...)來減少程式碼,如下所示:

let apples = ['🍎','🍇',...apples];  // <-- here

console.log( fruits );
//=> ["🍉","🍏"]

得到的輸出與普通寫法相同。

2. 合併陣列(在開頭位置)

普通寫法

假設我們想將apples陣列中的所有項新增到Fruits陣列的開頭,而不是像上一個示例中那樣放在末尾。我們可以使用

let apples = ['🍎','🍏'];
let fruits = ['🥭','🍌','🍒'];

// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits,apples)

console.log( fruits );
//=> ["🍎","🍏","🥭","🍌","🍒"]

現在紅蘋果和綠蘋果會在開頭位置合併而不是末尾。

簡寫方法

我們依然可以使用ES6擴充套件運算子(...)縮短這段長程式碼,如下所示:

let apples = ['🍎','🍏'];
let fruits = [...apples,'🥭','🍒'];  // <-- here

console.log( fruits );
//=> ["🍎","🍒"]

3. 克隆陣列

普通寫法

我們可以使用Array中的slice()方法輕鬆克隆陣列,如下所示:

let fruits = ['🍉','🍎'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=> ["🍉","🍎"]

簡寫方法

我們可以使用ES6擴充套件運算子(...)像這樣克隆一個數組:

let fruits = ['🍉','🍎'];
let cloneFruits = [...fruits];  // <-- here

console.log( cloneFruits );
//=> ["🍉","🍎"]

4. 解構賦值

普通寫法

在處理陣列時,我們有時需要將陣列“解包”成一堆變數,如下所示:

let apples = ['🍎','🍏'];
let redApple = apples[0];
let greenApple = apples[1];

console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

簡寫方法

我們可以通過解構賦值用一行程式碼實現相同的結果:

let apples = ['🍎','🍏'];
let [redApple,greenApple] = apples;  // <-- here

console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

5. 模板字面量

普通寫法

通常,當我們必須向字串新增表示式時,我們會這樣做:

// Display name in between two strings
let nawww.cppcns.comme = 'Palash';
console.log('Hello,' + name + '!');
//=> Hello,Palash!

// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10

簡寫方法

通過模板字面量,我們可以使用反引號(),這樣我們就可以將表示式包裝在${...}`中,然後嵌入到字串,如下所示:

// Display name in between two strings
let name = 'Palash';
console.log(`Hello,${name}!`);  // <-- No need to use + var + anymore
//=> Hello,Palash!

// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10

6. For迴圈

普通寫法

我們可以使用for迴圈像這樣迴圈遍歷一個數組:

let fruits = ['🍉','🍎'];

// Loop through each fruit
for (let index = 0; index < fruits.length; index++) { 
  console.log( fruits[index] );  // <-- get the fruit at current index
}

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

簡寫方法

我們可以使用for...of語句實現相同的結果,而程式碼要少得多,如下所示:

let fruits = ['🍉','🍎'];

// Using for...of statement 
for (let fruit of fruits) {
  console.log( fruit );
}

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

7. 箭頭函式

普通寫法

要遍歷陣列,我們還可以使用Array中的forEach()方法。但是需要寫很多程式碼,雖然比最常見的for迴圈要少,但仍然比for...of語句多一點:

let fruits = ['🍉','🍎'];

// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

簡寫方法

但是使用箭頭函式表示式,允許我們用一行編寫完整的迴圈程式碼,如下所示:

let fruits = ['🍉','🍎'];
fruits.forEach(fruit => console.log( fruit ));  // <-- Magic ✨

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

大多數時候我使用的是帶箭頭函式的forEach迴圈,這裡我把for...of語句和forEach迴圈都展示出來,方便大家根據自己的喜好使用程式碼。

8. 在陣列中查詢物件

普通寫法

要通過其中一個屬性從物件陣列中查詢物件的話,我們通常使用for迴圈:

let inventory = [
  {name: 'Bananas',quantity: 5},{name: 'Apples',quantity: 10},{name: 'Grapes',quantity: 2}
];

// Get the object with the name `Apples` inside the array
function getApples(arr,value) {
  for (let index = 0; index < arr.length; index++) {

    // Chwww.cppcns.comeck the value of this object property `name` is same as 'Apples'
    if (arr[index].name === 'Apples') {  //=> 🍎

      // A match was found,return this object
      return arr[index];
    }
  }
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples",quantity: 10 }

簡寫方法

哇!上面我們寫了這麼多程式碼來實現這個邏輯。但是使用Array中的find()方法和箭頭函式=>,允許我們像這樣一行搞定:

// Get the object with the name `Apples` inside the array
function getApples(arr,value) {
  return arr.find(obj => obj.name === 'Apples');  // <-- here
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples",quantity: 10 }

9. 將字串轉換為整數

普通寫法

let num = parseInt("10")

console.log( num )         //=> 10
console.log( typeof num )  //=> "number"

簡寫方法

我們可以通過在字串前新增+字首來實現相同的結果,如下所示:

let num =uQCmnYNrmD +"10";

console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true

10. 短路求值

普通寫法

如果我們必須根據另一個值來設定一個值不是falsy值,一般會使用if-else語句,就像這樣:

function getUserRole(role) {
  let userRole;

  // If role is not falsy value
  // set `userRole` as passed `role` value
  if (role) {
    userRole = role;
  } else {

    // else set the `userRole` as USER
    userRole = 'USER';
  }

  return userRole;
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

簡寫方法

但是使用短路求值(||),我們可以用一行程式碼執行此操作,如下所示:

function getUserRole(role) {
  return role || 'USER';  // <-- here
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

基本上,expression1 || expression2被評估為真表示式。因此,這就意味著如果第一部分為真,則不必費心求值表示式的其餘部分。

補充幾點

箭頭函式

如果你不需要this上下文,則在使用箭頭函式時程式碼還可以更短:

let fruits = ['🍉','🍎'];
fruits.forEach(console.log);

在陣列中查詢物件

你可以使用物件解構和箭頭函式使程式碼更精簡:

// Get the object with the name `Apples` inside the array
const getApples = array => array.find(({ name }) => name === "Apples");

let result = getApples(inventory);
console.log(result);
//=> { name: "Apples",quantity: 10 }

短路求值替代方案

const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = rhttp://www.cppcns.comole => role ? role : "USER";

最後,我想借用一段話來作結尾:

程式碼之所以是我們的敵人,是因為我們中的許多程式設計師寫了很多很多的狗屎程式碼。如果我們沒有辦法擺脫,那麼最好盡全力保持程式碼簡潔。

如果你喜歡寫程式碼——真的,真的很喜歡寫程式碼——你程式碼寫得越少,說明你的愛意越深。

到此這篇關於簡寫技巧的文章就介紹到這了,更多相關Script簡寫內容請搜尋我們www.cppcns.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!