ES6標(biāo)準(zhǔn)匯總(持續(xù)更新)

一、箭頭函數(shù)(Arrows Function)

ES6 為我們帶來了一種更簡(jiǎn)潔的書寫函數(shù)的方式,箭頭函數(shù)。在舊的標(biāo)準(zhǔn)中,我們是這樣書寫函數(shù)的:

 const myFunc = function() {
    const myVar = "value";
    return myVar;
  }

使用剪頭函數(shù),我們可以將其簡(jiǎn)化為:

const myFunc = () =>{
    const myVar = "value";
    return myVar;
}

進(jìn)一步簡(jiǎn)化

const myFunc = () => "value"

箭頭函數(shù)還可以傳參

// 將輸入的數(shù)乘以2,并返回
const doubler = (item)  => item * 2;

箭頭函數(shù)可以極大的化簡(jiǎn)高階函數(shù)的使用。所謂高階函數(shù),就是那些接受一個(gè)函數(shù)作為參數(shù)的函數(shù),常見的有:map(),filter(),reduce()。
在以前我們是這么寫高階函數(shù)的:

FBPosts.filter(function(post){
    return post.thumbnil  !== null && post.shares > 100 && post.likes>500;
})

利用箭頭函數(shù)可以這樣簡(jiǎn)化

FBPosts.filter((post)  =>post.thumbnil  !== null && post.shares > 100 && post.likes>500)

注:
(1)函數(shù)體內(nèi)的this對(duì)象,就是定義時(shí)所在的對(duì)象,而不是使用時(shí)所在的對(duì)象,箭頭函數(shù)繼承而來的this指向永遠(yuǎn)不變。

(2)不可以當(dāng)作構(gòu)造函數(shù),也就是說,不可以使用new命令,否則會(huì)拋出一個(gè)錯(cuò)誤。

(3)不可以使用arguments對(duì)象,該對(duì)象在函數(shù)體內(nèi)不存在。如果要用,可以用Rest參數(shù)代替。

(4)不可以使用yield命令,因此箭頭函數(shù)不能用作Generator函數(shù)。

二、為函數(shù)的參數(shù)設(shè)置默認(rèn)值

function greeting(name = "Anonymous") {
    return "Hello " + name;
  }
  console.log(greeting("John")); // 輸出 Hello John
  console.log(greeting()); // 輸出 Hello Anonymous

參數(shù)name的默認(rèn)值被設(shè)置為"Anonymous",所以在不傳參直接調(diào)用greeting()時(shí),輸出的是Hello Anonymous。

三、let、var、const命令

詳細(xì)可轉(zhuǎn)http://www.itdecent.cn/p/e48003dbd83e查看

四、rest參數(shù)(Rest Operator)

ES6中引入了rest參數(shù),其形式為...變量名。通過使用rest參數(shù),可以向函數(shù)傳入不同數(shù)量的參數(shù)

 function howMany(...args) {
    return "You have passed " + args.length + " arguments.";
  }
  console.log(howMany(0, 1, 2)); // 傳入三個(gè)參數(shù)
  console.log(howMany("string", null, [1, 2, 3], { })); // 傳入四個(gè)參數(shù)

rest 參數(shù)中的變量代表一個(gè)數(shù)組,所有數(shù)組特有的方法都可以用于這個(gè)變量

 function push(array, ...items) {
    items.forEach(function(item) {
      array.push(item);
      console.log(item);
    });
  }
  var a = [];
  push(a, 1, 2, 3)
  console.log(a)  //輸出 [1, 2, 3]

rest 參數(shù)后不能再有其他參數(shù),否則程序會(huì)報(bào)錯(cuò)。

五、擴(kuò)展運(yùn)算符(Spread Operator)

擴(kuò)展運(yùn)算符其實(shí)就是rest參數(shù)中的那三個(gè)點(diǎn)...其作用是:

  1. 拷貝數(shù)組對(duì)象
 console.log(...[1, 2, 3])
  // 1 2 3
  console.log(1, ...[2, 3, 4], 5)
  // 1 2 3 4 5
  [...document.querySelectorAll('div')]
  // [<div>, <div>, <div>]

擴(kuò)展運(yùn)算符拷貝數(shù)組,只有第一層是深拷貝,即對(duì)一維數(shù)組使用擴(kuò)展運(yùn)算符拷貝就屬于深拷貝。

const miniCalendar = [2021, [1, 2, 3, 4, 5, 6, 7], 1];

const copyArray = [...miniCalendar];
console.log(copyArray); // [ 2021, [ 1, 2, 3, 4, 5, 6, 7 ], 1 ]

copyArray[1][0] = 0;
copyArray[1].push(8);
copyArray[2] = 2;
console.log(copyArray); // [ 2021, [ 0, 2, 3, 4, 5, 6, 7, 8 ], 2 ]
console.log(miniCalendar); // [ 2021, [ 0, 2, 3, 4, 5, 6, 7, 8 ], 1 ]

拷貝對(duì)象,代碼如下:

const time = {
    year: 2021,
    month: 7,
    day: {
        value: 1,
    },
};
const copyTime = { ...time };
console.log(copyTime); // { year: 2021, month: 7, day: { value: 1 } }

擴(kuò)展運(yùn)算符拷貝對(duì)象也是只會(huì)在一層進(jìn)行深拷貝。

copyTime.day.value = 2;
copyTime.month = 6;
console.log(copyTime); // { year: 2021, month: 6, day: { value: 2 } }
console.log(time); // { year: 2021, month: 7, day: { value: 2 } }
  1. 合并操作
const halfMonths1 = [1, 2, 3, 4, 5, 6];
const halfMonths2 = [7, 8, 9, 10, 11, 12];

const allMonths = [...halfMonths1, ...halfMonths2];
console.log(allMonths); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

在合并對(duì)象時(shí),如果一個(gè)鍵已經(jīng)存在,它會(huì)被具有相同鍵的最后一個(gè)對(duì)象給替換。

const time1 = {
    month: 7,
    day: {
        value: 1,
    },
};
const time2 = {
    year: 2021,
    month: 8,
    day: {
        value: 10,
    },
};
const time = { ...time1, ...time2 };
console.log(time); // { month: 8, day: { value: 10 }, year: 2021 }
  1. 參數(shù)傳遞
const sum = (num1, num2) => num1 + num2;

console.log(sum(...[6, 7])); // 13
console.log(sum(...[6, 7, 8])); // 13

從上面的代碼看,函數(shù)定義了多少個(gè)參數(shù),擴(kuò)展運(yùn)算符傳入的值就是多少個(gè)。

在之前,如果我們想求數(shù)組中的最大值需要這樣寫:

var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // 返回 89

因?yàn)镸ath.max()方法只接受由逗號(hào)分隔的參數(shù)序列,比如Math.max(1, 2, 3),所以我們需要apply()進(jìn)行轉(zhuǎn)化。在ES6中,我們不再需要apply()方法,而是可以直接利用擴(kuò)展運(yùn)算符,其形式更易于理解。

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // 返回 89
const arrayNumbers = [1, 5, 9, 3, 5, 7, 10];
const min = Math.min(...arrayNumbers);
const max = Math.max(...arrayNumbers);
console.log(min); // 1
console.log(max); // 10
  1. 數(shù)組去重
    與 Set 一起使用消除數(shù)組的重復(fù)項(xiàng)
const arrayNumbers = [1, 5, 9, 3, 5, 7, 10, 4, 5, 2, 5];
const newNumbers = [...new Set(arrayNumbers)];
console.log(newNumbers); // [ 1,  5, 9, 3, 7, 10, 4, 2 ]
  1. 字符串轉(zhuǎn)字符數(shù)組
    String 也是一個(gè)可迭代對(duì)象,所以也可以使用擴(kuò)展運(yùn)算符 ... 將其轉(zhuǎn)為字符數(shù)組,如下:
const title = "china";
const charts = [...title];
console.log(charts); // [ 'c', 'h', 'i', 'n', 'a' ]

進(jìn)而可以簡(jiǎn)單進(jìn)行字符串截取,如下:

const title = "china";
const short = [...title];
short.length = 2;
console.log(short.join("")); // ch
  1. NodeList 轉(zhuǎn)數(shù)組

NodeList 對(duì)象是節(jié)點(diǎn)的集合,通常是由屬性,如 Node.childNodes 和方法,如 document.querySelectorAll 返回的。

NodeList 類似于數(shù)組,但不是數(shù)組,沒有 Array 的所有方法,例如find、map、filter 等,但是可以使用 forEach() 來迭代。

可以通過擴(kuò)展運(yùn)算符將其轉(zhuǎn)為數(shù)組.

const nodeList = document.querySelectorAll(".row");
const nodeArray = [...nodeList];
console.log(nodeList);
console.log(nodeArray);
image
  1. 解構(gòu)變量

(1)解構(gòu)數(shù)組

const [currentMonth, ...others] = [7, 8, 9, 10, 11, 12];
console.log(currentMonth); // 7
console.log(others); // [ 8, 9, 10, 11, 12 ]

(2)解構(gòu)對(duì)象

const userInfo = { name: "Crayon", province: "Guangdong", city: "Shenzhen" };
const { name, ...location } = userInfo;
console.log(name); // Crayon
console.log(location); // { province: 'Guangdong', city: 'Shenzhen' }

注:擴(kuò)展運(yùn)算符...只在某些特定的情況下才可以使用,比如函數(shù)的參數(shù)中,或者數(shù)組中。裸用擴(kuò)展運(yùn)算符程序會(huì)報(bào)錯(cuò)。

  var arr = [6, 89, 3, 45]
  const spreaded = ...arr; //報(bào)錯(cuò)

六、解構(gòu)賦值(Destructuring Assignment)

1.ES5中賦值是這樣的:

  var voxel = {x: 3.6, y: 7.4, z: 6.54 };
  var x = voxel.x; // x = 3.6
  var y = voxel.y; // y = 7.4
  var z = voxel.z; // z = 6.54

ES6中

 const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54

如果想賦值的變量與對(duì)象的屬性有不同的名稱

const { x : a, y : b, z : c } = voxel // a = 3.6, b = 7.4, c = 6.54

以上這種操作方法就叫解構(gòu)賦值。
2.解構(gòu)賦值也可以作用于嵌套的對(duì)象。

 const a = {
    start: { x: 5, y: 6},
    end: { x: 6, y: -9 }
  };
  const { start : { x: startX, y: startY }} = a;
  console.log(startX, startY); // 5, 6

3.利用解構(gòu)賦值,可以輕易的獲取數(shù)組的特定元素。

 const [a, b] = [1, 2, 3, 4, 5, 6];
  console.log(a, b); // 1, 2

  const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
  console.log(a, b, c); // 1, 2, 5

4.解構(gòu)賦值可以搭配擴(kuò)展運(yùn)算符使用

 const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
  console.log(a, b); // 1, 2
  console.log(arr); // [3, 4, 5, 7]

5.如果你想將一個(gè)對(duì)象當(dāng)參數(shù)傳入,你可能會(huì)想到這樣做:

  const profileUpdate = (profileData) => {
    const { name, age, nationality, location } = profileData;
    // 函數(shù)操作
  }

其實(shí)可以這樣簡(jiǎn)化,不用把整個(gè)對(duì)象都傳進(jìn)來,只需要傳入我們需要的那部分。

const profileUpdate = ({ name, age, nationality, location }) => {
    // 函數(shù)操作
  }

七、模板字符串(Template String)

ES6中引入了一種更強(qiáng)大的字符串寫法,被稱為模板字符串,用反引號(hào)( ` )標(biāo)識(shí)。

const person = {
    name: "Zodiac Hasbro",
    age: 56
  };

  //用模板字符串方式書寫的字符串,并將其賦給greeting變量
  const greeting = `Hello, my name is ${person.name}!
  I am ${person.age} years old.`;

  console.log(greeting); 
  // 輸出:
  // Hello, my name is Zodiac Hasbro!
  // I am 56 years old.

注:1. 模板字符串的標(biāo)識(shí)符是反引號(hào)(`) 而不是單引號(hào)(')。

  1. 輸出的字符串是多行的,我們?cè)谝膊恍枰猏n了
  2. 語法${}可以用來獲取變量,化簡(jiǎn)了之前用+來進(jìn)行字符串拼接的寫法。

八、定義對(duì)象的方法

以前我們是這樣定義的

  const person = {
    name: "Taylor",
    sayHello: function() {
      return `Hello! My name is ${this.name}.`;
    }
  };

在ES6中,可以將function關(guān)鍵詞省略。

  const person = {
    name: "Taylor",
    sayHello() {
      return `Hello! My name is ${this.name}.`;
    }
  };

九、 class語法糖

ES6中提供了一種新的語法創(chuàng)建對(duì)象,即使用class關(guān)鍵詞。需要注意的是,這里的class關(guān)鍵詞只是語法糖,并不具有像傳統(tǒng)的面向?qū)ο蟮恼Z言那樣的特性。

在ES5中,通常是這樣創(chuàng)建構(gòu)造函數(shù)的:

 var Person = function(name){
    this.name = name;
  }
  var person1 = new Person('Jim');

利用class語法糖,我們可以這樣寫:

 class Person {
    constructor(name){
      this.name = name;
    }
  }
  const person1 = new Person('Jim');
  1. 在由class定義的對(duì)象中,添加了構(gòu)造函數(shù)constructor(),構(gòu)造函數(shù)在new被調(diào)用時(shí)喚醒,創(chuàng)建一個(gè)新的對(duì)象。
  2. 用getters 和 setters封裝對(duì)象

在由class定義的對(duì)象中,存值函數(shù)和取值函數(shù)現(xiàn)在有了自己的關(guān)鍵字get和set,用法也更加簡(jiǎn)單。

  class Book {
    constructor(author) {
      this._author = author;
    }
    // getter
    get writer(){
      return this._author;
    }
    // setter
    set writer(updatedAuthor){
      this._author = updatedAuthor;
    }
  }
  const lol = new Book('anonymous');
  console.log(lol.writer);  // anonymous
  lol.writer = 'wut';
  console.log(lol.writer);  // wut

請(qǐng)注意調(diào)用存值函數(shù)和取值函數(shù)的方式:lol.writer。這種調(diào)用方式讓他們看起來并不像是函數(shù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容