溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

編寫JavaScript代碼的小技巧有哪些

發(fā)布時間:2021-08-02 14:08:25 來源:億速云 閱讀:110 作者:小新 欄目:web開發(fā)

小編給大家分享一下編寫JavaScript代碼的小技巧有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1 Array.includes 與條件判斷

一般我們判斷或用 ||

// condition
function test(fruit) {
 if (fruit == "apple" || fruit == "strawberry") {
  console.log("red");
 }
}

如果我們有更多水果

function test(fruit) {
 const redFruits = ["apple", "strawberry", "cherry", "cranberries"];

 if (redFruits.includes(fruit)) {
  console.log("red");
 }
}

2 Set 與去重

ES6 提供了新的數(shù)據(jù)結(jié)構(gòu) Set。它類似于數(shù)組,但是成員的值都是唯一的,沒有重復(fù)的值。Set 本身是一個構(gòu)造函數(shù),用來生成 Set 數(shù)據(jù)結(jié)構(gòu)。

數(shù)組去重

const arr = [3, 5, 2, 2, 5, 5];
const unique = [...new Set(arr)];
// [3,5,2]

Array.from 方法可以將 Set 結(jié)構(gòu)轉(zhuǎn)為數(shù)組。我們可以專門編寫使用一個去重的函數(shù)

function unique(array) {
 return Array.from(new Set(array));
}

unique([1, 1, 2, 3]); // [1, 2, 3]

字符去重

let str = [...new Set("ababbc")].join("");
console.log(str);
// 'abc'

另外 Set 是如此強(qiáng)大,因此使用 Set 可以很容易地實現(xiàn)并集(Union)、交集(Intersect)和差集(Difference)。

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

3 Map 與字典類型數(shù)據(jù)

一般而已,JavaScript 實現(xiàn)字典數(shù)據(jù)是基于 Object 對象。但是 JavaScript 的對象的鍵只能是字符串。對于編程來說有很多不便。 ES6 提供了 Map 數(shù)據(jù)結(jié)構(gòu)。它類似于 Object 對象,也是鍵值對的集合,但是“鍵”的范圍不限于字符串,各種類型的值,字符串、數(shù)值、布爾值、數(shù)組、對象等等都可以當(dāng)作鍵。

const resultMap = new Map()
 .set(-1, {text:'小于',color:'yellow')
 .set(0, {text:'等于',color:'black')
 .set(1, {text:'大于',color:'green')
 .set(null,{text:'沒有物品',color:'red'})

let state = resultMap.get(null)
// {text:'沒有物品',color:'red'}

Map 的遍歷順序就是插入順序

const map = new Map([["F", "no"], ["T", "yes"]]);

for (let key of map.keys) {
 console.log(key);
}
// "F"
// "T"

for (let value of map.value()) {
 console.log(value);
}
// "no"
// "yes"

4 函數(shù)式的方式處理數(shù)據(jù)

按照我的理解,函數(shù)式編程主張函數(shù)必須接受至少一個參數(shù)并返回一個值。所以所有的關(guān)于數(shù)據(jù)的操作,都可以用函數(shù)式的方式處理。

假設(shè)我們有這樣的需求,需要先把數(shù)組 foo 中的對象結(jié)構(gòu)更改,然后從中挑選出一些符合條件的對象,并且把這些對象放進(jìn)新數(shù)組 result 里。

let foo = [
 {
  name: "Stark",
  age: 21
 },
 {
  name: "Jarvis",
  age: 20
 },
 {
  name: "Pepper",
  age: 16
 }
];

//我們希望得到結(jié)構(gòu)稍微不同,age大于16的對象:
let result = [
 {
  person: {
   name: "Stark",
   age: 21
  },
  friends: []
 },
 {
  person: {
   name: "Jarvis",
   age: 20
  },
  friends: []
 }
];

從直覺上我們很容易寫出這樣的代碼:

let result = [];

//有時甚至是普通的for循環(huán)
foo.forEach(function(person){
  if(person.age > 16){
    let newItem = {
      person: person,
      friends: [];
    };
    result.push(newItem);
  }
})

使用函數(shù)式的寫法,可以優(yōu)雅得多

let result = foo
 .filter(person => person.age > 16)
 .map(person => ({
  person: person,
  friends: []
 }));

數(shù)組求和

let foo = [1, 2, 3, 4, 5];

//不優(yōu)雅
function sum(arr) {
 let x = 0;
 for (let i = 0; i < arr.length; i++) {
  x += arr[i];
 }
 return x;
}
sum(foo); // => 15

//優(yōu)雅
foo.reduce((a, b) => a + b); // => 15

5 compose 與函數(shù)組合

以下代碼稱為組合 compose

const compose = function(f, g) {
 return function(x) {
  return f(g(x));
 };
};

由于函數(shù)式編程大行其道,所以現(xiàn)在將會在 JavaScript 代碼看到大量的箭頭()=>()=>()=>的代碼。

ES6 版本 compose

const compose = (f, g) => x => f(g(x));

在 compose 的定義中, g 將先于 f 執(zhí)行,因此就創(chuàng)建了一個從右到左的數(shù)據(jù) 流。這樣做的可讀性遠(yuǎn)遠(yuǎn)高于嵌套一大堆的函數(shù)調(diào)用.

我們選擇一些函數(shù),讓它們結(jié)合,生成一個嶄新的函數(shù)。

reverse 反轉(zhuǎn)列表, head 取列表中的第一個元素;

const head = arr => arr[0];
const reverse = arr => [].concat(arr).reverse();

const last = compose(head, reverse);
last(["jumpkick", "roundhouse", "uppercut"]);
// "uppercut"

但是我們這個這個compose不夠完善,只能處理兩個函數(shù)參數(shù)。redux源碼有個很完備的compose函數(shù),我們借鑒一下。

function compose(...funcs){
 if (funcs.length === 0){
   return arg => arg
 }

 if (funcs.length === 1 ){
   return funcs[0]
 }

 return funcs.reduce((a,b)=>(...args) => a(b(...args)))
}

有了這個函數(shù),我們可以隨意組合無數(shù)個函數(shù)?,F(xiàn)在我們增加需求,組合出一個lastAndUpper函數(shù),內(nèi)容是先reverse 反轉(zhuǎn)列表, head 取列表中的第一個元素, 最后toUpperCase大寫。

const head = arr => arr[0];
const reverse = arr => [].concat(arr).reverse();
const toUpperCase = str => str.toUpperCase();

const last = compose(head, reverse);

const lastAndUpper = compose(toUpperCase, head, reverse,);

console.log(last(["jumpkick", "roundhouse", "uppercut"]));
// "uppercut"
console.log(lastAndUpper(["jumpkick", "roundhouse", "uppercut"]))
// "UPPERCUT"

以上是“編寫JavaScript代碼的小技巧有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI