1.map
var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95
var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined
因为一个key只能对应一个value,因此,屡次对一个key放入value,后面的值会把前面的值冲掉
2.set
Set和Map相似,也是一组key的集合,但不存储value。因为key不能重复,因此,在Set中,没有重复的key。
var s = new Set([1, 2, 3, 3, '3']);
s; // Set {1, 2, 3, "3"}
3.iterable
遍历Array能够采用下标循环,遍历Map和Set就没法使用下标。为了统一集合类型,ES6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型。
具备iterable类型的集合能够经过新的for ... of循环来遍历。
var a = [1, 2, 3]; for (var x of a) { }
4.rest
ES6标准引入了rest参数,上面的函数能够改写为:
function foo(a, b, ...rest) {
console.log('a = ' + a);
console.log('b = ' + b);
console.log(rest);
}
foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]
foo(1);
// 结果:
// a = 1
// b = undefined
// Array []
5.let
用let替代var能够申明一个块级做用域的变量
什么是块级做用域?for循环,{}
6.ES6标准引入了新的关键字const来定义常量,const与let都具备块级做用域
7.在ES6中,能够使用解构赋值,直接对多个变量同时赋值
数组
var [x, y, z] = ['hello', 'JavaScript', 'ES6'];
let [x, [y, z]] = ['hello', ['JavaScript', 'ES6']];
对象
var {name, age, passport} = person;
至关于 name = person.name;age = person.age;
var {name, address: {city, zip}} = person;
使用场景(交换2个变量)
var x=1, y=2; [x, y] = [y, x]
var {hostname:domain, pathname:path} = location;获取域名和路径,并重命名
function buildDate({year, month, day, hour=0, minute=0, second=0}) {
return new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
}
8.map函数
function pow(x) {
return x * x;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow);
9.reduce函数
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
10.filter
var arr = [1, 2, 4, 5, 6, 9, 10, 15];
var r = arr.filter(function (x) {
return x % 2 !== 0;
});
r; // [1, 5, 9, 15]
11.箭头函数(至关于匿名函数)
(x,y) => { x + y } 单条语句时,可省略{}
x => ({ foo: x }) 返回对象
12.class
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}