1 ES6是什么?

ES6是ECMAScript 6的简写.

ECMAScript 6也称为ES6和ECMAScript 2015.

下面是维基百科中对ECMAScript的定义。

1
ECMAScript (or ES) is a scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript, so as to foster multiple independent implementations.

Ecma International: 一个制定技术标准的国际组织

ECMA-262: 由Ecma International发布。它包含了脚本语言的标准。

ECMAScript 与 JavaScript的区别

ECMAScript是一个标准,而JavaScript是一个脚本编程语言,它遵循了ECMAScript标准。

2 基础玩法

2.1 let

var可以随意覆盖之前声明的变量

你可以覆盖变量声明,而不报错。

1
2
3
4
var camper = 'James';
var camper = 'David';
console.log(camper);
// => 'David'

在实际使用过程中,你可能偶然的覆盖了之前的变量而你并不希望这样。

let解决了覆盖的问题

1
2
let camper = 'James';
let camper = 'David'; // throws an error

作用域的差别

1
2
3
4
5
6
7
8
9
10
var printNumTwo;
for (var i = 0; i < 3; i++) {
if(i === 2){
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3

上面的i是全局变量,所以返回的结果是3。

1
2
3
4
5
6
7
8
9
10
11
12
13
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"

上面的i是局部变量,仅在循环体内有效。因此结果为2。

2.2 const

const限定的变量是只读的。

但是仍然可以改写const限定的数组

1
2
3
4
5
"use strict";
const s = [5, 6, 7];
s = [1, 2, 3]; // throws error, trying to assign a const
s[2] = 45; // works just as it would with an array declared with var or let
console.log(s); // returns [5, 6, 45]

使用Object.freeze保证对象不被更改

1
2
3
4
5
6
7
8
9
let obj = {
name:"FreeCodeCamp",
review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad"; //will be ignored. Mutation not allowed
obj.newProp = "Test"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: "FreeCodeCamp", review:"Awesome"}

2.3 箭头函数

箭头函数就是匿名函数,与C++中的lambda类似。

1
2
3
const sum = (a, b) => {
return a + b;
}

或者省略return关键字,写成这样

1
const sum = (a, b) => a + b;

用箭头函数你可以很简单的用少量代码完成你需要的功能。

例如:求数组中所有大于0的数字(不包含浮点数)的平方。

1
2
3
4
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => arr.filter((v) => Number.isInteger(v) && v > 0).map((v) => Math.pow(v, 2));
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

你看,如此美丽而大方。

2.4 函数的默认参数

1
2
3
4
5
function greeting(name = "Anonymous") {
return "Hello " + name;
}
console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous

2.5 Rest 操作符

即不定参数。

1
2
3
4
5
6
7
const sum = (function() {
"use strict";
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); // 6

2.6 Spread 操作符

如下面的例子,将数组拆解到函数参数中。

1
2
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89

但是你只能在函数参数或者数组中。

1
2
3
const spreaded = ...arr; // will throw a syntax error
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2 = [...arr1]; // Correct

使用Spread合并数组

1
2
3
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']

2.7 解构(Destructuring)

对对象进行解构

1
2
var voxel = {x: 3.6, y: 7.4, z: 6.54 };
const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54

深层次的解构

1
2
3
4
5
6
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

对数组进行解构

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

交换数值

1
2
3
4
5
6
7
let a = 8, b = 6;
(() => {
"use strict";
[a, b] = [b, a];
})();
console.log(a); // should be 6
console.log(b); // should be 8

对数组切片. (只能对尾部切片,不能在中间切)

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

在函数参数中玩解构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = (function() {
"use strict"; // do not change this line
return function half({max, min}) {
return (max + min) / 2.0;
};
})();
console.log(stats); // should be object
console.log(half(stats)); // should be 28.015

2.8 模板字符串

  • 用反引号,支持多行
  • 用变量(或表达式)占位
1
2
3
4
5
6
7
8
9
10
11
12
const person = {
name: "Zodiac Hasbro",
age: 56
};

// Template literal with multi-line and string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;

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

2.9 更简洁的对象声明

1
const getMousePosition = (x, y) => ({ x, y });

上面的函数与下面的等价:

1
2
3
4
const getMousePosition = (x, y) => ({
x: x,
y: y
});

2.10 更简洁的函数声明

1
2
3
4
5
6
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};

上面的代码与下面的等价:

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

2.11 class

ES6中可以方便的使用class关键字创建对象。

注意:此处的class只是一个语法,和C++中的类(面向对象范式)不一样。

此处的class只是创建了一个函数。

1
2
3
4
5
6
class SpaceShuttle {
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');

使用setter和getter隐藏实现细节

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

2.12 import

1
2
import { function } from "file_path_goes_here"
// We can also import variables the same way!

import与require的区别

require需要加载依赖模块的所有,而import只加载需要的函数和变量。

用 * 来import所有

1
2
import * as object_with_name_of_your_choice from "file_path_goes_here"
object_with_name_of_your_choice.imported_function

2.13 export

1
2
3
4
5
const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString } //How to export functions.
export const foo = "bar"; //How to export variables.

你也可以写成下面这样:

1
2
3
4
5
const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const foo = "bar";
export { capitalizeString, foo }

export default

导出默认的变量,只能有一个。

1
2
3
4
// export-default.js
export default function(){
console.log('foo');
};
1
2
3
// import-default.js
import customName from './export-default';
customName();//foo;

3 Reference