国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

ES2015+ 備忘清單

快速瀏覽 ES2015、ES2016、ES2017、ES2018 及以后的 JavaScript 新特性

常用

塊范圍

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // 只在這個`if`里面
  }
}

Const

const a = 1

let 是新的 var。 常量(const) 就像 let 一樣工作,但不能重新分配。 請參閱:Let 和 const

反引號字符串

插值

const message = `Hello ${name}`

多行字符串

const str = `
hello
world
`

模板和多行字符串。 請參閱:模板字符串

二進(jìn)制和八進(jìn)制文字

let bin = 0b1010010
let oct = 0o755

請參閱:二進(jìn)制和八進(jìn)制文字

指數(shù)運算符

const byte = 2 ** 8
// 同: Math.pow(2, 8)

新方法

新的字符串方法

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   " 
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")

新的數(shù)字方法

Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false

新的 Math 方法

Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2

新的 Array 方法

// 返回一個真實的數(shù)組
Array.from(document.querySelectorAll("*"))
// 類似于 new Array(...),但沒有特殊的單參數(shù)行為
Array.of(1, 2, 3)

請參閱: 新方法

class Circle extends Shape {

構(gòu)造函數(shù)

  constructor (radius) {
    this.radius = radius
  }

方法

  getArea () {
    return Math.PI * 2 * this.radius
  }

調(diào)用超類方法

  expand (n) {
    return super.expand(n) * Math.PI
  }

靜態(tài)方法

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}

原型的語法糖。 請參閱:

私有類

javascript 默認(rèn)字段是公共的(public),如果需要注明私有,可以使用(#

class Dog {
  #name;
  constructor(name) {
    this.#name = name;
  }
  printName() {
    //只能在類內(nèi)部調(diào)用私有字段
    console.log(`你的名字是${this.#name}`)
  }
}

const dog = new Dog("putty")
//console.log(this.#name) 
//Private identifiers are not allowed outside class bodies.
dog.printName()

靜態(tài)私有類

class ClassWithPrivate {
  static #privateStaticField;
  static #privateStaticFieldWithInitializer = 42;

  static #privateStaticMethod() {
    // …
  }
}

Promises

做出承諾

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})

用于異步編程。 請參閱:Promises

使用 Promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })

在 finally 中使用 Promise

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => {
    /* 獨立于成功/錯誤的邏輯 */
  })

當(dāng)承諾被履行或被拒絕時,處理程序被調(diào)用

Promise 函數(shù)

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}

async 函數(shù)是使用函數(shù)的另一種方式。 請參閱:異步函數(shù)

解構(gòu) Destructuring

解構(gòu)賦值

Arrays

const [first, last] = ['Nikola', 'Tesla']

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}

支持匹配數(shù)組和對象。 請參閱:解構(gòu)

默認(rèn)值

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores

// Result:
// math === 22, sci === 33, arts === 50

可以在解構(gòu)數(shù)組或?qū)ο髸r分配默認(rèn)值

函數(shù)參數(shù)

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}

greet({ name: 'Larry', greeting: 'Ahoy' })

對象和數(shù)組的解構(gòu)也可以在函數(shù)參數(shù)中完成

默認(rèn)值

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}

greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

重新分配鍵

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}

printCoordinates({ left: 25, top: 90 })

此示例將 x 分配給 left 鍵的值

循環(huán)

for (let {title, artist} of songs) {
  ···
}

賦值表達(dá)式也在循環(huán)中工作

對象解構(gòu)

const { id, ...detail } = song;

使用 rest(...) 運算符單獨提取一些鍵和對象中的剩余鍵

擴展運算符 Spread

對象擴展

與對象擴展

const options = {
  ...defaults,
  visible: true
}

沒有對象擴展

const options = Object.assign(
  {}, defaults,
  { visible: true })

對象擴展運算符允許您從其他對象構(gòu)建新對象。 請參閱:對象傳播

數(shù)組擴展

具有數(shù)組擴展

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]

沒有數(shù)組擴展

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

擴展運算符允許您以相同的方式構(gòu)建新數(shù)組。 請參閱:擴展運算符

函數(shù) Functions

函數(shù)參數(shù)

默認(rèn)參數(shù)

function greet (name = 'Jerry') {
  return `Hello ${name}`
}

Rest 參數(shù)

function fn(x, ...y) {
  // y 是一個數(shù)組
  return x * y.length
}

擴展

fn(...[1, 2, 3])
// 與 fn(1, 2, 3) 相同

Default(默認(rèn)), rest, spread(擴展)。 請參閱:函數(shù)參數(shù)

箭頭函數(shù)

箭頭函數(shù)

setTimeout(() => {
  ···
})

帶參數(shù)

readFile('text.txt', (err, data) => {
  ...
})

隱式返回

arr.map(n => n*2)
// 沒有花括號 = 隱式返回
// 同: arr.map(function (n) { return n*2 })
arr.map(n => ({
  result: n*2
}))
// 隱式返回對象需要在對象周圍加上括號

類似函數(shù),但保留了 this。 請參閱:箭頭函數(shù)

參數(shù)設(shè)置默認(rèn)值

function log(x, y = 'World') {
  console.log(x, y);
}

log('Hello')          // Hello World
log('Hello', 'China') // Hello China
log('Hello', '')      // Hello

與解構(gòu)賦值默認(rèn)值結(jié)合使用

function foo({x, y = 5} = {}) {
  console.log(x, y);
}

foo() // undefined 5

name 屬性

function foo() {}
foo.name // "foo"

length 屬性

function foo(a, b){}
foo.length // 2

Objects

速記語法

module.exports = { hello, bye }

同下:

module.exports = {
  hello: hello, bye: bye
}

請參閱:對象字面量增強

方法

const App = {
  start () {
    console.log('running')
  }
}
// 同: App = { start: function () {···} }

請參閱:對象文字增強

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}

請參閱:對象字面量增強

計算屬性名稱

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// 同: handlers = { 'onclick': true }

請參閱:對象字面量增強

提取值

const fatherJS = { age: 57, name: "張三" }
Object.values(fatherJS)
// [57, "張三"]
Object.entries(fatherJS)
// [["age", 57], ["name", "張三"]]

Modules 模塊

Imports 導(dǎo)入

import 'helpers'
// 又名: require('···')

import Express from 'express'
// 又名: const Express = require('···').default || require('···')

import { indent } from 'helpers'
// 又名: const indent = require('···').indent

import * as Helpers from 'helpers'
// 又名: const Helpers = require('···')

import { indentSpaces as indent } from 'helpers'
// 又名: const indent = require('···').indentSpaces

import 是新的 require()。 請參閱:Module imports

Exports 導(dǎo)出

export default function () { ··· }
// 又名: module.exports.default = ···

export function mymethod () { ··· }
// 又名: module.exports.mymethod = ···

export const pi = 3.14159
// 又名: module.exports.pi = ···

const firstName = 'Michael';
const lastName = 'Jackson';
const year = 1958;
export { firstName, lastName, year };

export * from "lib/math";

export 是新的module.exports。 請參閱:Module exports

as 關(guān)鍵字重命名

import {
  lastName as surname // 導(dǎo)入重命名
} from './profile.js';

function v1() { ... }
function v2() { ... }

export { v1 as default };
// 等同于 export default v1;

export {
  v1 as streamV1,           // 導(dǎo)出重命名
  v2 as streamV2,           // 導(dǎo)出重命名
  v2 as streamLatestVersion // 導(dǎo)出重命名
};

動態(tài)加載模塊

button.addEventListener('click', event => {
  import('./dialogBox.js')
    .then(dialogBox => {
      dialogBox.open();
    })
    .catch(error => {
      /* Error handling */
    })
});

ES2020提案 引入 import() 函數(shù)

import() 允許模塊路徑動態(tài)生成

const main = document.querySelector('main')

import(`./modules/${someVariable}.js`)
  .then(module => {
    module.loadPageInto(main);
  })
  .catch(err => {
    main.textContent = err.message;
  });

import.meta

ES2020import 命令添加了一個元屬性 import.meta,返回當(dāng)前模塊的元信息

new URL('data.txt', import.meta.url)

Node.js 環(huán)境中,import.meta.url返回的總是本地路徑,即 file:URL 協(xié)議的字符串,比如 file:///home/user/foo.js

導(dǎo)入斷言(Import Assertions)

靜態(tài)導(dǎo)入

import json from "./package.json" assert {type: "json"}
// 導(dǎo)入 json 文件中的所有對象

動態(tài)導(dǎo)入

const json = 
     await import("./package.json", { assert: { type: "json" } })

Generators

Generator 函數(shù)

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}

let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2

情況很復(fù)雜。 請參閱:Generators

For..of + 迭代器(iterator)

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (var n of fibonacci) {
  // 在 1000 處截斷序列
  if (n > 1000) break;
  console.log(n);
}

用于迭代生成器和數(shù)組。 請參閱:For..of iteration

與 Iterator 接口的關(guān)系

var gen = {};
gen[Symbol.iterator] = function* () {
  yield 1;
  yield 2;
  yield 3;
};

[...gen] // => [1, 2, 3]

Generator 函數(shù)賦值給 Symbol.iterator 屬性,從而使得 gen 對象具有了 Iterator 接口,可以被 ... 運算符遍歷了

Symbol.iterator 屬性

function* gen() { /* some code */ }
var g = gen();

g[Symbol.iterator]() === g // true

gen 是一個 Generator 函數(shù),調(diào)用它會生成一個遍歷器對象g。它的 Symbol.iterator 屬性,也是一個遍歷器對象生成函數(shù),執(zhí)行后返回它自己

另見