ECMAScript1.0, 1998年发布ECMAScript2.0, 1999年发布ECMAScript3.0ECMAScript4.0 流产,原因是不向下兼容,语法和新特性都太过激进,遭到各大浏览器厂商的抵制ECMAScript5.0, 项目代号为harmony(和谐),即ES5ECMAScript2015,也称ES6.
{
let a = 10;
var b = 20;
}
console.log(a); // ReferenceError: a is not defined
console.log(b); // 20
会发生变量提升,内层变量覆盖外层变量
var tmp = new Date();
function f(){
console.log(tmp);
if(false) {
var tmp = 'hello world';
}
}
f(); // undefined
用来计数的临时变量意外地成为全局变量
var str = 'hello';
for(var i=0; i < str.length; i++) {
console.log(str[i]);
}
console.log(i); // 5
console.log(tmp); //ReferenError
let tmp = 10;
let代替var来声明变量
typeof x; // ReferenError
let x;
function bar( x=y, y=2){
return [x,y];
}
bar(); //报错 ReferenceError: y is not defined
下面哪个会报错
function bar1(arg){
let arg = 0;
}
function bar2(arg){
{
let arg = 0;
}
}
bar1();
bar2();
const foo = {};
foo.age = 10;
console.log(foo.age); // 10
foo = {}; // TypeError: "foo" is read-only
// abc.js
export const X = 1;
export const Y = 2;
//test1.js
import * as a from './abc';
console.log(a.X); // 1
console.log(a.Y); // 2
//test2.js
import {X,Y} from './abc';
console.log(X); // 1
console.log(Y); // 2
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)
let [a,b,c] = [1,2,3];
如果解构不成功,变量的值就等于undefined
var [foo] = [];
var [bar, foo] = [1];
“模式匹配”
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []`
let [x, y] = [1, 2, 3];
x // 1
y // 2
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
var [foo = true] = [];
foo // true
function f() {
console.log('aaa');
}
let [x = f()] = [1];
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
变量必须与属性同名,才能取到正确的值
var { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
var { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };
var { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x:y = 3} = {};
y // 3
var {x:y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
字符串的解构赋值
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
数值和布尔值的解构赋值
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
function example() {
return [1, 2, 3];
}
var [a, b, c] = example();
函数参数的定义更加灵活
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
提取JSON数据
var jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
输入模块的指定方法更加清晰
const { SourceMapConsumer, SourceNode } = require("source-map");
遍历Map结构更加方便
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"
优点是可以识别大于0xFFFF的字符编码,比如中文: 𠮷
下标位置ES6又提供了三种新方法。
布尔值,表示是否找到了参数字符串。布尔值,表示参数字符串是否在源字符串的头部。布尔值,表示参数字符串是否在源字符串的尾部。
var s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true, 等同于 s.startsWith('Hello',0); 意思是前5个字符是否以"Hello"结束
s.includes('Hello', 6) // false
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana"
ES7推出了字符串补全长度的功能padStart用于头部补全,padEnd用于尾部补全
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '
为数值补全指定位数
'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"
提示字符串格式化
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
$('#result').append(
'There are ' + basket.count + ' ' +
'items in your basket, ' +
'' + basket.onSale +
' are on sale!'
);
$('#result').append(`
There are ${basket.count} items
in your basket, ${basket.onSale}
are on sale!
`);
模板字符串中嵌入变量
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
模板字符串之中还能调用函数
var x = 1;
var y = 2;
`${x} + ${y} = ${x + y}` // "1 + 2 = 3"
function fn() {
return "Hello World";
}
`foo ${fn()} bar` // foo Hello World bar
const tmpl = addrs => `
Hello ${name}
${addrs.map(addr => `
aaaaa, ${addr.first}
`).join('')}
`;
不建议用模板字符串干这些var regex = new RegExp('xyz', 'i');
var regex = new RegExp(/xyz/i);
// 等价于
var regex = /xyz/i;
var regex = new RegExp(/abc/ig, 'i')
原有正则对象的修饰符是ig,它会被第二个参数i覆盖/^\uD83D/u.test('\uD83D\uDC2A') // falsevar s = '𠮷';
/^.$/.test(s) // false
/^.$/u.test(s) // true
/a{2}/.test('aa') // true
/a{2}/u.test('aa') // true
/𠮷{2}/.test('𠮷𠮷') // false
/𠮷{2}/u.test('𠮷𠮷') // true
y修饰符确保匹配必须从剩余的第一个位置开始var s = 'aaa_aa_a';
var r = /a+_/y;
r.exec(s) // ["aaa_"]
r.exec(s) // ["aa_"]
17个与数学相关的方法ES7新增了一个指数运算符(**),目前Babel转码器已经支持。
2 ** 2 // 4
2 ** 3 // 8
let a = 2;
a **= 2;
// 等同于 a = a * a;
// 非严格模式
(function(){
console.log(0o11 === 011);
})() // true
Number.isFinite(15); // true
Number.isFinite(0.8); // true
Number.isFinite(NaN); // false
Number.isNaN(NaN) // true
Number.isNaN(15) // false
Number.isNaN('15') // false
ES6将全局方法parseInt()和parseFloat(),移植到Number对象上面,行为完全保持不变。
// ES5的写法
parseInt('12.34') // 12
parseFloat('123.45#') // 123.45
// ES6的写法
Number.parseInt('12.34') // 12
Number.parseFloat('123.45#') // 123.45
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']
let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]
//表示将从3号位直到数组结束的成员(4和5),复制到从0号位开始的位置,结果覆盖了原来的1和2。
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
//找出数组中第一个小于0的成员
[1, 4, -5, 10].find( function(n){
return n < 0;
});
// -5
位置,用法跟find()方法一样。键名的遍历,values()是对键值的遍历,entries()是对键值对的遍历for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, NaN].includes(NaN); // true
function log(x, y) {
y = y || 'World';
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
function foo(x = 5) {
let x = 1; // error
}
对象的解构赋值作为参数
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined, 5
foo({x: 1}) // 1, 5
foo({x: 1, y: 2}) // 1, 2
foo() // TypeError: Cannot read property 'x' of undefined
双重默认值
function fetch(url, { method = 'GET' } = {}) {
console.log(method);
}
fetch('http://example.com')
// "GET"
参数默认值是变量,其作用域在先函数,后全局
var x = 1;
function f(x, y = x) {
console.log(y);
}
f(2) // 2
f() // 1
参数的默认值是一个函数, 该函数的作用域是其声明时所在的作用域
let foo = 'outer';
function bar(function(x){
return foo;
}) {
let foo = 'inner';
console.log(func()); // outer
}
bar();
例如,利用rest参数,可以向add函数传入任意数目的参数
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2, 5, 3) // 10
主要用于函数调用,传递参数
function add(x, y) {
return x + y;
}
var numbers = [4, 38];
add(...numbers) // 42
// add(4,38);
合并数组
// ES5
[1, 2].concat(more)
// ES6
[1, 2, ...more]
var arr1 = ['a', 'b'];
var arr2 = ['c'];
var arr3 = ['d', 'e'];
// ES5的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
[...'hello']
// [ "h", "e", "l", "l", "o" ]
任何Iterator接口的对象,都可以用扩展运算符转为真正的数组
// Map和Set结构,Generator函数
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]
比如:
var f = v => v;
//等同于:
var f = function(v) {
return v;
};
var f = () => 5;
// 等同于
var f = function () { return 5 };
var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2) {
return num1 + num2;
};
函数体内的this对象,是定义时所在的对象,而不是使用时所在的对象
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });
// id: 42
箭头函数可以让this指向固定化,这种特性很有利于封装回调函数
// ES6
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
// ES5
function foo() {
var _this = this;
setTimeout(function () {
console.log('id:', _this.id);
}, 100);
}
function f(x){
return g(x);
}
下面不属于尾调用
// 情况一
function f(x){
let y = g(x);
return y;
}
// 情况二
function f(x){
return g(x) + 1;
}
// 情况三
function f(x){
g(x);
// return undefined;
}
function f() {
let m = 1;
let n = 2;
return g(m + n);
}
f();
// 等同于
function f() {
return g(3);
}
f();
// 等同于
g(3);
普通递归,计算n的阶乘,最多需要保存n个调用记录,复杂度 O(n)
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
factorial(5) // 120
function factorial(n, total) {
if (n === 1) return total;
return factorial(n - 1, n * total);
}
factorial(5, 1) // 120
function currying(fn, n) {
return function (m) {
return fn.call(this, m, n);
};
}
function tailFactorial(n, total) {
if (n === 1) return total;
return tailFactorial(n - 1, n * total);
}
const factorial = currying(tailFactorial, 1);
factorial(5); //只传了一个参数
var foo = 'bar';
var baz = {foo};
baz // {foo: "bar"}
// 等同于
var baz = {foo: foo};
function f(x, y) {
return {x, y};
}
// 等同于
function f(x, y) {
return {x: x, y: y};
}
方法也可以简写
var o = {
method() {
return "Hello!";
}
};
// 等同于
var o = {
method: function() {
return "Hello!";
}
};
module.exports = { getItem, setItem, clear };
// 等同于
module.exports = {
getItem: getItem,
setItem: setItem,
clear: clear
};
在 ES5 中只能使用标识符定义属性
var obj = {
foo: true,
abc: 123
};
ES6 允许用表达式作为对象的属性名
let propKey = 'foo';
let obj = {
\[propKey\]: true
};
Object.is 比较两个值是否相等
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
var target = { a: 1 };
var source1 = { b: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
class Point {
constructor(x, y) {
Object.assign(this, {x, y});
}
}
为对象添加方法
Object.assign(SomeClass.prototype, {
someMethod(arg1, arg2) {
···
}
});
// 等同于下面的写法
SomeClass.prototype.someMethod = function (arg1, arg2) {
···
};
function clone(origin) {
return Object.assign({}, origin);
}
const merge = (target, ...sources) => Object.assign(target, ...sources);
ES5引入了Object.keys方法,返回一个数组,成员是键名
var obj = { foo: "bar", baz: 42 };
Object.keys(obj)
//["foo", "baz"]
var obj = { foo: "bar", baz: 42 };
Object.values(obj)
//["bar", 42]
let obj = { one: 1, two: 2 };
for (let [k, v] of Object.entries(obj)) {
console.log(`${JSON.stringify(k)}: ${JSON.stringify(v)}`);
}
// "one": 1
// "two": 2
const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
// 2 3 5 4
Set初始化
// 例一
var set = new Set([1, 2, 3, 4, 4]);
[...set]
// [1, 2, 3, 4]
// 例二
var items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5
向Set加入值的时候,不会发生类型转换,Set内部用 === 判断值是否相等
1. 5 和 '5'是不同的值,类型不一样
2. NaN 被认为是相同的值,只能存一个
3. {} object被认为是不同的值,可以存多个
let set = new Set();
let a = NaN;
let b = NaN;
set.add(a);
set.add(b);
set // Set {NaN}
let set = new Set();
set.add({});
set.size // 1
set.add({});
set.size // 2
clear():清除所有成员,没有返回值。
s.add(1).add(2).add(2);
// 注意2被加入了两次
s.size // 2
s.has(1) // true
s.has(2) // true
s.has(3) // false
s.delete(2);
s.has(2) // false
Array.from方法可以将Set结构转为数组
var items = new Set([1, 2, 3, 4, 5]);
var array = Array.from(items);
//去除数组重复成员
function dedupe(array) {
return Array.from(new Set(array));
}
dedupe([1, 1, 2, 3]) // [1, 2, 3]
//或者用扩展运算符方式去除数组的重复成员
function dedupe(array) {
return [...new Set(array)];
}
Set 结构没有键名,只有键值,所以keys方法和values方法的行为完全一致
let set = new Set(['red', 'green', 'blue']);
for (let item of set.keys()) {
console.log(item);
}
for (let item of set.values()) {
console.log(item);
}
for (let item of set.entries()) {
console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
for (let x of set) {
console.log(x);
}
let set = new Set(['red', 'green', 'blue']);
let arr = [...set];
// ['red', 'green', 'blue']
数组的map和filter方法也可以用于Set
let set = new Set([1, 2, 3]);
set = new Set([...set].map(x => x * 2));
// 返回Set结构:{2, 4, 6}
let set = new Set([1, 2, 3, 4, 5]);
set = new Set([...set].filter(x => (x % 2) == 0));
// 返回Set结构:{2, 4}
如果需要“键值对”的数据结构,Map比Object更合适
var m = new Map();
var o = {p: 'Hello World'};
m.set(o, 'content')
m.get(o) // "content"
m.has(o) // true
m.delete(o) // true
m.has(o) // false
Map也可以接受一个数组作为参数
var map = new Map([
['name', '张三'],
['title', 'Author']
]);
map.size // 2
map.has('name') // true
map.get('name') // "张三"
map.has('title') // true
map.get('title') // "Author"
let map = new Map();
map
.set(1, 'aaa')
.set(1, 'bbb');
map.get(1) // "bbb"
只有对同一个对象的引用,Map结构才将其视为同一个键
var map = new Map();
map.set(['a'], 555);
map.get(['a']) // undefined, 内存地址不一样
var map = new Map();
var a = ['a'];
map.set(a, 555);
map.get(a) // 555
size属性, 返回Map结构的成员总数
set(key, value) , 如果key已经有值,则值会被更新
// set方法返回的是Map本身,因此可以采用链式写法
let map = new Map()
.set(1, 'a')
.set(2, 'b')
.set(3, 'c');
var m = new Map();
var hello = function() {console.log("hello");}
m.set(hello, "Hello ES6!") // 键是函数
m.get(hello) // Hello ES6!
map.keys()
let map = new Map([
['F', 'no'],
['T', 'yes'],
]);
for (let key of map.keys()) {
console.log(key); // F,T
}
for (let value of map.values()) {
console.log(value); // no, yes
}
map.entries()
let map = new Map([
['F', 'no'],
['T', 'yes'],
]);
for (let item of map.entries()) {
console.log(item[0], item[1]);
}
// 或者
for (let [key, value] of map.entries()) {
console.log(key, value);
}
// 等同于使用map.entries()
for (let [key, value] of map) {
console.log(key, value);
}
使用扩展运算符(...)
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
[...map.keys()]
// [1, 2, 3]
[...map.values()]
// ['one', 'two', 'three']
[...map.entries()]
// [[1,'one'], [2, 'two'], [3, 'three']]
[...map]
// [[1,'one'], [2, 'two'], [3, 'three']]
模拟具有next方法的迭代器
var it = makeIterator(['a', 'b']);
it.next() // { value: "a", done: false }
it.next() // { value: "b", done: false }
it.next() // { value: undefined, done: true }
function makeIterator(array) {
var nextIndex = 0;
return {
next: function() {
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{value: undefined, done: true};
}
};
}
无限运行的迭代器,ID生成器
var it = idMaker();
it.next().value // '0'
it.next().value // '1'
it.next().value // '2'
// ...
function idMaker() {
var index = 0;
return {
next: function() {
return {value: index++, done: false};
}
};
}
for...of循环可以代替数组实例的forEach方法
const arr = ['red', 'green', 'blue'];
arr.forEach(function (element, index) {
console.log(element); // red green blue
});
for(let a of arr){
console.log(a); // red green blue
}
var es6 = new Map();
es6.set("edition", 6);
es6.set("committee", "TC39");
es6.set("standard", "ECMA-262");
for (var [name, value] of es6) {
console.log(name + ": " + value);
}
// edition: 6
// committee: TC39
// standard: ECMA-262
let arrayLike = { length: 2, 0: 'a', 1: 'b' };
// 报错
for (let x of arrayLike) {
console.log(x);
}
// 正确
for (let x of Array.from(arrayLike)) {
console.log(x);
}
for (var key of Object.keys(someObject)) {
console.log(key + ': ' + someObject[key]);
}