前端必須要掌握的 ES6 語法總結(jié)

let 與 const

let

let a = 1
let b = 2,
  c = 3

console.log(a, b, c) // 1 2 3

let 用于聲明一個塊級作用域的變量,所以它不會造成變量提升。聲明后的變量不允許重復(fù)聲明。let 解決了 var 造成變量提升、覆蓋和泄露等問題。

const

const a = 1

console.log(a) // 1

const 用于聲明常量,即不允許重新賦值(修改變量指向的內(nèi)存地址)和重復(fù)聲明。const 也不會造成變量提升。

有關(guān) varletconst 的詳細介紹,可以參考 JS:var、let 與 const 總結(jié)

解構(gòu)

對象解構(gòu)

基礎(chǔ)用法

const tom = {
  name: "Tom",
  age: 18,
  city: "Beijing",
}

const { name, age } = tom
console.log(name, age) // Tom 18

屬性重命名

const { name: myName } = tom
console.log(myName) // Tom

設(shè)置默認值

const { city, country = "China" } = tom
console.log(city, country) // Beijing China

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

const arr = [1, 2, 3]

const [a, b, c] = arr

console.log(a, b, c) // 1 2 3

如果數(shù)組的長度不一致,可以使用 ... 來解構(gòu),只保留長度一致的部分。

const arr = [1, 2, 3]

const [a, ...rest] = arr

console.log(a, rest) // 1 [2, 3]

const [a, b, c, ...rest] = arr

console.log(a, b, c, rest) // 1 2 3 []

參數(shù)解構(gòu)

function foo({ name, age }) {
  console.log(name, age)
}

foo({ name: "Tom", age: 18 }) // Tom 18

function bar([a, b, c]) {
  console.log(a, b, c)
}

bar([1, 2, 3]) // 1 2 3

字符串解構(gòu)

const str = "hello"

const [a, b, c] = str

console.log(a, b, c) // h e l l

字符串相關(guān)

模板字符串

const name = "Tom"
const age = 18

const str = `Hello, I'm ${name}, ${age} years old.`

console.log(str) // Hello, I'm Tom, 18 years old.

模板字符串的出現(xiàn),是字符串的一個重要特性,它可以提供更加靈活的字符串拼接方式。

startsWith()

startsWith() 方法用于判斷字符串是否以指定的字符串開頭,如果是,返回 true,否則返回 false。

const str = "hello"

console.log(str.startsWith("h")) // true
console.log(str.startsWith("e")) // false

endsWith()

startsWith() 的兄弟,用于判斷字符串是否以指定的字符串結(jié)尾,如果是,返回 true,否則返回 false。

const str = "hello"

console.log(str.endsWith("o")) // true
console.log(str.endsWith("e")) // false

includes()

用于判斷字符串是否包含指定的字符串,如果是,返回 true,否則返回 false。

const str = "hello"

console.log(str.includes("h")) // true
console.log(str.includes("e")) // true
console.log(str.includes("x")) // false

repeat()

用于將一個字符串重復(fù) n 次,如果 n 是小于 1 的數(shù)值,則返回一個空字符串。

const str = "ha~"

console.log(str.repeat(3)) // ha~ha~ha~

數(shù)字相關(guān)

Math.sign()

用于獲取一個數(shù)的符號,如果是正數(shù),則返回 1,如果是負數(shù),則返回 -1,如果是 0,則返回 0。

const a = -3
const b = 0
const c = 3

console.log(Math.sign(a)) // -1
console.log(Math.sign(b)) // 0
console.log(Math.sign(c)) // 1

數(shù)組相關(guān)

Array.from()

用于將一個偽數(shù)組(也成為類數(shù)組)或者可迭代對象轉(zhuǎn)換成一個真正的數(shù)組。

將偽數(shù)組轉(zhuǎn)換為數(shù)組

const arrayLike = {
  0: "a",
  1: "b",
  2: "c",
  length: 3,
}

console.log(Array.from(arrayLike)) // ['a', 'b', 'c']

將字符串轉(zhuǎn)換為數(shù)組

const str = "hello"

console.log(Array.from(str)) // ['h', 'e', 'l', 'l', 'o']

將 Set 轉(zhuǎn)換為數(shù)組

const mySet = new Set([1, 2, 3])

console.log(Array.from(mySet)) // [1, 2, 3]

將 Map 轉(zhuǎn)換為數(shù)組

const myMap = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3],
])

console.log(Array.from(myMap)) // [['a', 1], ['b', 2], ['c', 3]]

Array.of()

Array.of() 用于將一組值(用逗號隔開)轉(zhuǎn)換成一個數(shù)組。

const arr = Array.of(1, 2, 3)

console.log(arr) // [1, 2, 3]

find()

用于獲取數(shù)組中滿足條件(函數(shù)形式返回)的第一個元素。

const studentList = [
  {
    id: 1,
    name: "Tom",
    age: 12,
  },
  {
    id: 2,
    name: "Jerry",
    age: 13,
  },
  {
    id: 3,
    name: "Bob",
    age: 11,
  },
]

const student = studentList.find(item => item.age === 13)

console.log(student) // { id: 2, name: 'Jerry', age: 13 }

findIndex()

用于獲取數(shù)組中滿足條件的第一個元素的索引。

const studentList = [
  {
    id: 1,
    name: "Tom",
    age: 12,
  },
  {
    id: 2,
    name: "Jerry",
    age: 13,
  },
  {
    id: 3,
    name: "Bob",
    age: 11,
  },
]

const index = studentList.findIndex(item => item.age === 13)

console.log(index) // 1

fill()

fill() 方法用于用指定值填充數(shù)組。

const arr = [1, 1, 1, 1, 1]

console.log(arr.fill(0)) // [0, 0, 0, 0, 0]
console.log(arr.fill(0, 1)) // [1, 0, 0, 0, 0]
console.log(arr.fill(0, 1, 3)) // [1, 0, 0, 1, 1]

其中第一個參數(shù)就是指定值,第二個參數(shù)為起始索引,默認為 0,第三個參數(shù)為終止索引,默認為數(shù)組的長度,即填充到最后一位。

對象

Object.assign()

Object.assign() 用于將所有可枚舉屬性的值從一個或多個源對象復(fù)制(淺拷貝)到目標對象。

const groupA = {
  a: 1,
  b: 2,
  c: 3,
}

const groupB = {
  b: 4,
  c: 5,
  d: 6,
}

const all = Object.assign(groupA, groupB)

console.log(all) // { a: 1, b: 4, c: 5, d: 6 }

對于重復(fù)的元素,將以后面的(最新的)為準。

簡潔表示法

ES6 允許在對象 {} 里面,直接寫入變量或函數(shù)名,然后作為對象內(nèi)的屬性名。

const str = "hello"

const arr = [1, 2, 3]

const obj = {
  str, // 等同于 str: str
  arr, // 等同于 arr: arr
  num: 1,
}

console.log(obj) // { str: 'hello', arr: [1, 2, 3], num: 1 }

在函數(shù)內(nèi)也可以:

function test() {
  let x = 1,
    y = 2
  return { x, y }
}

console.log(test()) // { x: 1, y: 2 }

函數(shù)

箭頭函數(shù)

const foo = () => {
  console.log("foo")
}

foo() // foo

箭頭函數(shù)的語法比函數(shù)表達式更簡潔,并且沒有自己的 this,arguments,super 或 new.target。很適用于需要匿名函數(shù)的地方。

const arr = [1, 2, 3, 4, 5]

const bigger = arr.filter(item => item >= 3)

console.log(bigger) // [ 3, 4, 5 ]

參數(shù)默認值

function foo(x = 1, y = 2) {
  console.log(x, y)
}

foo() // 1 2
foo(2) // 2 2
foo(2, 3) // 2 3
foo(undefined, 3) // 1 3

參數(shù)展開

function foo(x, y, ...rest) {
  console.log(x, y, rest)
}

foo(1, 2, 3, 4, 5) // 1 2 [3, 4, 5]

... 一般放在參數(shù)的最后一位,用于獲取函數(shù)調(diào)用時所有未被使用的參數(shù)。

新的數(shù)據(jù)結(jié)構(gòu)

Set

const set = new Set([1, 2, 3, 4, 5])

console.log(set.has(1)) // true
console.log(set.has(6)) // false
console.log(set.size) // 5

Set 數(shù)據(jù)結(jié)構(gòu)是一個無序的集合,每個元素都唯一。

Map

Map 和對象 {} 類似,都是一些鍵值對的集合。但是更加靈活。

const map = new Map()

map.set("a", 1)

console.log(map) // Map(1) { 'a' => 1 }

Map 的鍵可以是任意值,甚至可以是函數(shù)、對象

function b() {}

map.set(b, 2)

console.log(map) // Map(2) { 'a' => 1, [Function: b] => 2 }

Map 可以直接被迭代

map.forEach((value, key) => {
  console.log(key + " = " + value)
})

// 輸出
// a = 1
// function b() {} = 2

Map 的鍵值對個數(shù)可以通過 size 獲取

console.log(map.size) // 2

通用

擴展運算符(展開語法)

const arr = [1, 2]
console.log(...arr) // 1 2

const str = "hello"
console.log(...str) // h e l l o

for in

const obj = { a: 1, b: 2 }

for (let key in obj) {
  console.log(key) // a b
}

for in 可以遍歷對象的鍵名。

for of

const arr = [1, 2]

for (let item of arr) {
  console.log(item) // 1 2
}

for of 可以遍歷數(shù)組的成員。

class

class Student {
  constructor(name) {
    this.name = name
  }

  sayName() {
    console.log(`My name is ${this.name}`)
  }
}

const student = new Student("Bob")

student.sayName() // My name is Bob

class 關(guān)鍵字用于創(chuàng)建一個類??梢岳斫鉃?ES5 的構(gòu)造函數(shù)的語法糖。

關(guān)于構(gòu)造函數(shù)與 class,可以參考 JS:構(gòu)造函數(shù)總結(jié)。

Promise

const asyncFunc = new Promise((resolve, rejcet) => {
  Math.random() > 0.5 ? resolve("fulfilled") : rejcet("rejected")
})

asyncFunc
  .then(data => {
    console.log(data) // fulfilled
  })
  .catch(err => {
    console.log(err) // rejected
  })
  .finally(() => {
    console.log("finally")
  })

Promise 是 ES6 新增的一種異步操作解決方案。Promise 對象的狀態(tài)可以有 3 個:pending、fulfilledrejected。當狀態(tài)發(fā)生改變時,會觸發(fā)相應(yīng)的回調(diào)函數(shù)。

關(guān)于更多 Promise 的介紹,可以參考:JS:手寫實現(xiàn) Promise。

async/await

async function hello() {
  return await Promise.resolve("Hello")
}

hello().then(console.log) // Hello

async/await 是 ES2017 中新增的異步解決方案。簡單來說,它們是基于 Promise 的語法糖,使異步代碼更易于編寫和閱讀。

async 函數(shù)返回一個 Promise 對象,await 關(guān)鍵字只能用在 async 函數(shù)中,不能用在其他函數(shù)中。

關(guān)于更多 async/await 的介紹,可以參考 JS:async/await 總結(jié)

Proxy

Proxy 用于創(chuàng)建一個對象的代理,從而實現(xiàn)基本操作的攔截和自定義(如屬性查找、賦值、枚舉、函數(shù)調(diào)用等)??梢源砣魏螌ο?,包括數(shù)組。可以直接監(jiān)聽整個對象而非屬性,比 Object.defineProperty() 更加簡潔,更加高效,更加安全。

Proxy 返回的一個新對象,可以只操作新的對象達到目的。

const cat = {
  name: "Tom",
}

const myCat = new Proxy(cat, {
  get(target, property) {
    console.log(`我的 ${property} 被讀取了`)
    return property in target ? target[property] : undefined
  },
  set(target, property, value) {
    console.log(`我的 ${property} 被設(shè)置成了 ${value}`)
    target[property] = value
    return true
  },
})

myCat.name // expected output: 我被讀取了:name
myCat.name = "Kitty" // expected output: 我的 name 被設(shè)置成了 Kitty

Reflect

Reflect 對象主要用于訪問和修改對象的屬性。

const cat = {
  name: "Tom",
}

Reflect.set(cat, "age", 5)

console.log(Reflect.get(cat, "name")) // Tom

console.log(cat.age) // 5

console.log(Reflect.has(cat, "name")) // true

console.log(Reflect.ownKeys(cat)) // ['name', 'age']

ReflectObject 看似雷同,但存在許多差異,具體可以參考 比較 Reflect 和 Object 方法

Symbol

const mySymbol = Symbol()

console.log(typeof mySymbol) // "symbol"

console.log(Symbol() === Symbol()) // false

Symbol 是 ES6 新增的一種基本數(shù)據(jù)類型。Symbol 表示一個獨一無二的值。

Generator

Generator 是 ES6 新增的一種異步編程模型。

Generator 函數(shù)是一個狀態(tài)機,遇到 yield 就會暫停執(zhí)行,并返回一個 { value, done } 的對象,value 屬性表示返回的值,done 屬性表示是否完成。

function* helloWorldGenerator() {
  yield "hello"
  yield "world"
  return "ending"
}

const hw = helloWorldGenerator()

console.log(hw.next()) // { value: 'hello', done: false }
console.log(hw.next()) // { value: 'world', done: false }
console.log(hw.next()) // { value: 'ending', done: true }

Module

Module 是 ES6 新增的模塊化語法,可以將代碼拆分成多個文件,并且可以通過 importexport 來導(dǎo)入和導(dǎo)出。

// math.js
export function add(x, y) {
  return x + y
}
// app.js
import { add } from "./math"

console.log(add(1, 2)) // 3

如何將 ES6+ 轉(zhuǎn)換為 ES5

  • 為什么要將 ES6+ 轉(zhuǎn)換為 ES5?

    因為 ES6+ 是 JavaScript 的新語法,我們雖然可以在開發(fā)時使用,但是直接運行在瀏覽器中的話,許多語法瀏覽器是不支持的,所以要將 ES6+ 轉(zhuǎn)換為 ES5。

  • 安裝 Babel

    Babel 是一個 JavaScript 編譯器,可以將 ES6+ 轉(zhuǎn)換為 ES5。

    npm i @babel/core babel-loader @babel/preset-env -D
    

    @babel/core 是 Babel 的核心包。

    babel-loader 是 Webpack 的 loader,用于在 Webpack 打包時調(diào)用 Babel,從而將 ES6+ 轉(zhuǎn)換為 ES5。

    @babel/preset-env 提供了一些預(yù)置的 Babel 配置,這是一個智能預(yù)設(shè),只要安裝這一個 preset,就會根據(jù)你設(shè)置的目標瀏覽器,自動將代碼中的新特性轉(zhuǎn)換成目標瀏覽器支持的代碼。

    -D 表示安裝到 package.json 中的開發(fā)依賴。

  • 在 Webpack 中使用 Babel

    module.exports = {
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader",
              options: {
                presets: ["@babel/preset-env"],
              },
            },
          },
        ],
      },
    }
    

參考資料:

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

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

  • ES6 是什么 ECMAScript 2015 于2015年6月正式發(fā)布 可以使用babel語法轉(zhuǎn)換器,支持低端瀏...
    我是嘉煒閱讀 234評論 0 2
  • ES6阮一峰老師的書已經(jīng)出到第三版了,從中受益匪淺,第二版讀了三遍,在項目中常用到的一些語法和方法做些總結(jié) 字符串...
    任雨丶閱讀 15,940評論 0 11
  • ECMAScript 簡介 它是一種由ECMA組織(前身為歐洲計算機制造商協(xié)會)制定和發(fā)布的腳本語言規(guī)范 而我們學...
    冬來Angus閱讀 1,109評論 0 0
  • ES6阮一峰老師的書已經(jīng)出到第三版了,從中受益匪淺,第二版讀了三遍,在項目中常用到的一些語法和方法做些總結(jié) 字符串...
    程芬KELA閱讀 622評論 0 0
  • ES6語法跟babel: 一、首先我們來解釋一下什么是ES? ES的全稱是ECMAScript。1996 11 ,...
    Mooya_閱讀 1,166評論 0 0

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