变量的解构赋值
// 以前的变量赋值
let a = 1;
let b = 2;
let c = 3;
ES6 允许写成下面这样。
// 数组的解构赋值
let [a, b, c] = [1, 2, 3];
a // "1"
b // "2"
c // "3"
// 对象的解构赋值
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
// 默认值
var {x, y = 5} = {x: 1};
x // 1
y // 5
// 函数的解构赋值(默认值)
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
结构赋值的用途
(1)交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x]
// 交换变量x和y的值。
(2)从函数返回多个值,函数只能返回一个值,如果要返回多个值,只能将它们放在数组或对象里返回。
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
(3)函数参数的定义,解构赋值可以方便地将一组参数与变量名对应起来。
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
(4)提取 JSON 数据
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
(5)函数参数的默认值,指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || ‘default foo’;这样的语句
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
(6)遍历 Map 结构
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// 如果只想获取键名,或者只想获取键值,可以写成下面这样。
// 获取键名
for (let [key] of map) {
// ...
}
// 获取键值
for (let [,value] of map) {
// ...
}
(7)输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");
CLASS
ES5 构造函数
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
console.log(p.x); // 1
console.log(p.y); // 2
class 基本语法
上面的代码用ES6的“类”改写,就是下面这样。
//定义类
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p = new Point(1, 2);
console.log(p.x); // 1
console.log(p.y); // 2