ES6 速查表 🔥 - 你所需要的一切🚀
嘿,开发人员,这是一份针对初学者和经验丰富的开发人员所需的 ES6 备忘单!
那么让我们开始吧!!
🎉赠品
我们正在 Udemy 上免费赠送您所需的任何课程。课程价格不限。
参与方式如下:
- 👍 回复此帖
- ✉️ 订阅我们的新闻通讯
--> 点击此处获取可下载的 PDF 版本
块级作用域
让
function fn () {
let x = 0
if (true) {
let x = 1 // only inside this `if`
}
}
常量
const a = 1
let
是新的var
。常量的工作方式与 类似let
,但不能重新赋值。
检查:Let 和 const
反引号字符串
插值
const message = `Hello ${name}`
多行字符串
const str = `
hello
world
`
模板和多行字符串。
检查:模板字符串
二进制和八进制文字
let bin = 0b1010010
let oct = 0o755
检查:二进制和八进制文字
新方法
新的字符串方法
"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")
检查:新方法
课程
class Circle extends Shape {
构造函数
constructor (radius) {
this.radius = radius
}
方法
getArea () {
return Math.PI * 2 * this.radius
}
调用超类方法
expand (n) {
return super.expand(n) * Math.PI
}
静态方法
static createFromDiameter(diameter) {
return new Circle(diameter / 2)
}
}
原型的语法糖。
检查:类
指数运算符
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
承诺
做出承诺
new Promise((resolve, reject) => {
if (ok) { resolve(result) }
else { reject(error) }
})
用于异步编程。
检查:Promises
使用承诺
promise
.then((result) => { ··· })
.catch((error) => { ··· })
将 Promise 与 finally 结合使用
promise
.then((result) => { ··· })
.catch((error) => { ··· })
.finally(() => { // logic independent of success/error })
当承诺实现或被拒绝时,处理程序就会被调用。
Promise 函数
Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)
异步等待
async function run () {
const user = await getUser()
const tweets = await getTweets(user)
return [user, tweets]
}
async
函数是使用函数的另一种方式。
检查:异步函数
解构
解构赋值
数组
const [first, last] = ['Nikola', 'Tesla']
对象
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
支持匹配数组和对象。
检查:解构
默认值
const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50
解构数组或对象时可以分配默认值。
函数参数
function greet({ name, greeting }) {
console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })
对象和数组的解构也可以在函数参数中完成。
默认值
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
。
循环
for (let {title, artist} of songs) {
···
}
赋值表达式在循环中也能起作用。
对象解构
const { id, ...detail } = song;
使用 rest (...) 运算符单独提取一些键,然后提取对象中的剩余键
传播
对象传播
带有对象扩展
const options = {
...defaults,
visible: true
}
无对象传播
const options = Object.assign(
{}, defaults,
{ visible: true })
对象扩展运算符允许您从其他对象构建新对象。
检查:物体扩散
数组扩展
使用数组展开
const users = [
...admins,
...editors,
'rstacruz'
]
没有数组扩展
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
扩展运算符允许您以相同的方式构建新数组。
检查:扩展运算符
功能
函数参数
默认参数
function greet (name = 'Jerry') {
return `Hello ${name}`
}
剩余参数
function fn(x, ...y) {
// y is an Array
return x * y.length
}
传播
fn(...[1, 2, 3])
// same as fn(1, 2, 3)
默认、剩余、扩展。
检查:函数参数
粗箭头
粗箭头
setTimeout(() => {
···
})
带有参数
readFile('text.txt', (err, data) => {
...
})
隐式回报
numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
result: n * 2
}))
// Implicitly returning objects requires parentheses around the object
类似函数,但this
保留了原有的样式。
检查:粗箭头
对象
简写语法
module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }
检查:对象字面量增强
方法
const App = {
start () {
console.log('running')
}
}
// Same as: App = { start: function () {···} }
检查:对象字面量增强
Getter 和 Setter
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
检查:对象字面量增强
计算属性名称
let event = 'click'
let handlers = {
[`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
检查:对象字面量增强
提取值
const fatherJS = { age: 57, name: "Brendan Eich" }
Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
模块
导入
import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces
import
是新的require()
。
检查:模块导入
出口
export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···
export
是新的module.exports
。
检查:模块导出
生成器
生成器
function* idMaker () {
let id = 0
while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2
这很复杂。
检查:发电机
For..of 迭代
for (let i of iterable) {
···
}
用于遍历生成器和数组。
检查:For..of 迭代
参考
⚡️赠品⚡️
我们正在 Udemy 上免费赠送您所需的任何课程。任何价格,任何课程。
参与赠品活动的步骤
--> 回复此帖子
--> 订阅我们的新闻通讯<-- 非常重要--> 在Twitter
上关注我<-- 中奖概率 x2
获奖者将于 5 月 1 日通过 Twitter 公布
非常感谢您阅读这篇文章。
评论您所知道的任何技巧和窍门!
请点赞、分享和评论
另请阅读:


400+ JavaScript 面试题🎓及答案🌠
Lorenzo 为 World In Dev 撰稿 ・ 2021 年 4 月 27 日
订阅我们的时事通讯,即可直接在您的电子邮件中收到我们的每周回顾!
加入我们的Discord与我们一起参加黑客马拉松/参与我们的赠品活动!
谢谢阅读!
文章来源:https://dev.to/worldindev/es6-cheatsheet-all-you-need-1iaf