最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

2019 年編寫現(xiàn)代 JavaScript 代碼的5個(gè)小技巧(小結(jié))

 更新時(shí)間:2019年01月15日 11:48:32   作者:廖振廷  
這篇文章主要介紹了2019 年編寫現(xiàn)代 JavaScript 代碼的5個(gè)小技巧,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

內(nèi)容基本是今年從其他大神的文章學(xué)習(xí)到的東西。分享給大家:

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è)構(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ù)組。我們可以專門編寫使用一個(gè)去重的函數(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 可以很容易地實(shí)現(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 實(shí)現(xiàn)字典數(shù)據(jù)是基于 Object 對(duì)象。但是 JavaScript 的對(duì)象的鍵只能是字符串。對(duì)于編程來說有很多不便。 ES6 提供了 Map 數(shù)據(jù)結(jié)構(gòu)。它類似于 Object 對(duì)象,也是鍵值對(duì)的集合,但是“鍵”的范圍不限于字符串,各種類型的值,字符串、數(shù)值、布爾值、數(shù)組、對(duì)象等等都可以當(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ù)必須接受至少一個(gè)參數(shù)并返回一個(gè)值。所以所有的關(guān)于數(shù)據(jù)的操作,都可以用函數(shù)式的方式處理。

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

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

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

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

let result = [];

//有時(shí)甚至是普通的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)在將會(huì)在 JavaScript 代碼看到大量的箭頭()=>()=>()=>的代碼。

ES6 版本 compose

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

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

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

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

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

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

但是我們這個(gè)這個(gè)compose不夠完善,只能處理兩個(gè)函數(shù)參數(shù)。redux源碼有個(gè)很完備的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)))
}

有了這個(gè)函數(shù),我們可以隨意組合無數(shù)個(gè)函數(shù)。現(xiàn)在我們?cè)黾有枨?,組合出一個(gè)lastAndUpper函數(shù),內(nèi)容是先reverse 反轉(zhuǎn)列表, head 取列表中的第一個(gè)元素, 最后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"

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

黄龙县| 克什克腾旗| 江城| 三河市| 米林县| 阿图什市| 吉首市| 黔西县| 盐山县| 高清| 山西省| 建阳市| 泰顺县| 安国市| 吉林省| 应城市| 沙坪坝区| 班玛县| 三门峡市| 延寿县| 霍州市| 大厂| 阿勒泰市| 盐池县| 新安县| 福鼎市| 迭部县| 北宁市| 万州区| 南投县| 泰安市| 筠连县| 健康| 雷山县| 城步| 梅河口市| 海南省| 湘乡市| 镇安县| 陇西县| 福安市|