欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript簡寫技巧

 更新時間:2021年08月25日 10:24:01   作者:前端新世界  
這篇文章主要介紹了JavaScript簡寫技巧,運(yùn)用簡寫技巧,可以加快開發(fā)速度,讓開發(fā)工作事半功倍,大家感興趣的話可以參考本篇文章

1. 合并數(shù)組

普通寫法

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

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

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

簡寫方法

我們可以通過使用ES6擴(kuò)展運(yùn)算符(...)來減少代碼,如下所示:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples];  // <-- here

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

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

2. 合并數(shù)組(在開頭位置)

普通寫法

假設(shè)我們想將apples數(shù)組中的所有項添加到Fruits數(shù)組的開頭,而不是像上一個示例中那樣放在末尾。我們可以使用

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

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

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

現(xiàn)在紅蘋果和綠蘋果會在開頭位置合并而不是末尾。

簡寫方法

我們依然可以使用ES6擴(kuò)展運(yùn)算符(...)縮短這段長代碼,如下所示:

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

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

3. 克隆數(shù)組

普通寫法

我們可以使用Array中的slice()方法輕松克隆數(shù)組,如下所示:

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

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

簡寫方法

我們可以使用ES6擴(kuò)展運(yùn)算符(...)像這樣克隆一個數(shù)組:

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

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

4. 解構(gòu)賦值

普通寫法

在處理數(shù)組時,我們有時需要將數(shù)組“解包”成一堆變量,如下所示:

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

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

簡寫方法

我們可以通過解構(gòu)賦值用一行代碼實(shí)現(xiàn)相同的結(jié)果:

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

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

5. 模板字面量

普通寫法

通常,當(dāng)我們必須向字符串添加表達(dá)式時,我們會這樣做:

// Display name in between two strings
let name = '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

簡寫方法

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

// 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循環(huán)

普通寫法

我們可以使用for循環(huán)像這樣循環(huán)遍歷一個數(shù)組:

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語句實(shí)現(xiàn)相同的結(jié)果,而代碼要少得多,如下所示:

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

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

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

7. 箭頭函數(shù)

普通寫法

要遍歷數(shù)組,我們還可以使用Array中的forEach()方法。但是需要寫很多代碼,雖然比最常見的for循環(huán)要少,但仍然比for...of語句多一點(diǎn):

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

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

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

簡寫方法

但是使用箭頭函數(shù)表達(dá)式,允許我們用一行編寫完整的循環(huán)代碼,如下所示:

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

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

大多數(shù)時候我使用的是帶箭頭函數(shù)的forEach循環(huán),這里我把for...of語句和forEach循環(huán)都展示出來,方便大家根據(jù)自己的喜好使用代碼。

8. 在數(shù)組中查找對象

普通寫法

要通過其中一個屬性從對象數(shù)組中查找對象的話,我們通常使用for循環(huán):

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++) {

    // Check 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 }

簡寫方法

哇!上面我們寫了這么多代碼來實(shí)現(xiàn)這個邏輯。但是使用Array中的find()方法和箭頭函數(shù)=>,允許我們像這樣一行搞定:

// 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. 將字符串轉(zhuǎn)換為整數(shù)

普通寫法

let num = parseInt("10")

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

簡寫方法

我們可以通過在字符串前添加+前綴來實(shí)現(xiàn)相同的結(jié)果,如下所示:

let num = +"10";

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

10. 短路求值

普通寫法

如果我們必須根據(jù)另一個值來設(shè)置一個值不是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"

簡寫方法

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

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

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

基本上,expression1 || expression2被評估為真表達(dá)式。因此,這就意味著如果第一部分為真,則不必費(fèi)心求值表達(dá)式的其余部分。

補(bǔ)充幾點(diǎn)

箭頭函數(shù)

如果你不需要this上下文,則在使用箭頭函數(shù)時代碼還可以更短:

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

在數(shù)組中查找對象

你可以使用對象解構(gòu)和箭頭函數(shù)使代碼更精簡:

// 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 = role => role ? role : "USER";

最后,我想借用一段話來作結(jié)尾:

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

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

到此這篇關(guān)于JavaScript簡寫技巧的文章就介紹到這了,更多相關(guān)JavaScript簡寫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JS中強(qiáng)制類型轉(zhuǎn)換的實(shí)現(xiàn)

    JS中強(qiáng)制類型轉(zhuǎn)換的實(shí)現(xiàn)

    JavaScript中有幾種強(qiáng)制類型轉(zhuǎn)換的方法,可以將一個數(shù)據(jù)類型轉(zhuǎn)換為另一個數(shù)據(jù)類型,具有一定的參考價值,感興趣的可以了解一下
    2023-05-05
  • JavaScript使用Math.Min返回兩個數(shù)中較小數(shù)的方法

    JavaScript使用Math.Min返回兩個數(shù)中較小數(shù)的方法

    這篇文章主要介紹了JavaScript使用Math.Min返回兩個數(shù)中較小數(shù)的方法,涉及javascript中Math.Min方法的使用技巧,非常具有實(shí)用價值,需要的朋友可以參考下
    2015-04-04
  • 詳解maxlength屬性在textarea里奇怪的表現(xiàn)

    詳解maxlength屬性在textarea里奇怪的表現(xiàn)

    這篇文章主要介紹了maxlength屬性在textarea里奇怪的表現(xiàn)的相關(guān)資料,需要的朋友可以參考下
    2015-12-12
  • js圖片放大鏡實(shí)例講解(必看篇)

    js圖片放大鏡實(shí)例講解(必看篇)

    下面小編就為大家?guī)硪黄猨s圖片放大鏡實(shí)例講解(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • kmock javascript 單元測試代碼

    kmock javascript 單元測試代碼

    javascript其實(shí)是非常需要單元測試的,但是qmock總感覺不好使?或是文檔的新舊有問題,反正我暫時是只需要函數(shù)調(diào)用的次數(shù)判斷,結(jié)果就寫了個kmock
    2011-02-02
  • JavaScript中出現(xiàn)亂碼的處理心得

    JavaScript中出現(xiàn)亂碼的處理心得

    最近項目中遇到些字符串亂碼問題,解決后有些心得,記錄于此。
    2009-12-12
  • 用js實(shí)現(xiàn)控件的隱藏及style.visibility的使用

    用js實(shí)現(xiàn)控件的隱藏及style.visibility的使用

    用js控制控件的隱藏,使用style.visibility實(shí)現(xiàn) ,具體代碼如下,感興趣的朋友可以參考下哈,希望對大家有所幫助
    2013-06-06
  • ESLint詳解及在WebStorm中的應(yīng)用步驟

    ESLint詳解及在WebStorm中的應(yīng)用步驟

    ESLint是一種JavaScript代碼檢查工具,開發(fā)者可以通過自定義規(guī)則進(jìn)行代碼風(fēng)格和質(zhì)量的控制,使用ESLint的過程包括安裝、初始化配置、配置規(guī)則、運(yùn)行ESLint檢查代碼、與編輯器集成,以及與構(gòu)建工具集成等,需要的朋友可以參考下
    2024-09-09
  • JS仿百度自動下拉框模糊匹配提示

    JS仿百度自動下拉框模糊匹配提示

    這篇文章主要介紹了JS仿百度自動下拉框模糊匹配提示 的相關(guān)資料,需要的朋友可以參考下
    2016-07-07
  • JS array數(shù)組檢測方式解析

    JS array數(shù)組檢測方式解析

    這篇文章主要介紹了JS array數(shù)組檢測方式解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05

最新評論