今天主要修改了小窝的语录功能,从原有的 Post 表单提交方式改为 Ajax + API 提交,为以后全站 API 化,可能实现的前后端分离做好准备。晚上则是重新复习了一波 ES6 的变量解构(因为此前看过阮一峰的教程),主要内容如下:
let [a, b, c] = [5, 1, 2];
// 等同于 let a = 5, b = 1, c = 2;
let arr = [4, 5];
let [x, y, z] = arr; // 等同于 let x = 4, y = 5, z = undefined
let [a, b, c] = [1, [1, 2], {id: 1}]; // 等同于 let a = 1, b = [1, 2], c = {id: 1}
let [a, [b], d] = [1, [2, 3], 4]; // 等同于 let a = 1, b = 2, d = 4;
let arr2 = [100, 200];
let [x = 1, y = 2] = arr2;
// 等同于 let x = 100, 200,因为有内容,如果不用默认参数,就是
// let x = arr2[0] || 1, y = arr2[1] || 2;
let [x = 1, y = 2] = [6]; // 等同于 let x = 6, y = 2
let [x = 10, y = 20] = []; // 等同于 let x = 10, y = 20
let [x, y = 100] = [10]; // 等同于 let x = 10, y = 100
// 以下两种情况只有 undefined 会变成 1
let [x = 1] = [null]
let [x = 1] = [undefined]
以此同时,还了解了对象的解构,它和数组也很相似,就是解构出来的变量名如果要改,必须使用 :
说明一下。左侧为匹配模式,右侧为修改的变量名
let obj = {
name: "Paul",
age: 19,
id: 1
}
let {name, age} = obj; // 等同于 let name = obj.name, age = obj.age
let {name:n, age:a} = obj; // 等同于 let n = obj.name, a = obj.age
let {a} = {x: 1, y: 2}; // 无法匹配
let {x:a} = {x: 1, y: 2}; // 等同于 let a = 1,a 作为变量,x 作为匹配模式
let {x = 1, y = 10} = {x:undefined}; // 等同于 let x = 1, y = 10
let {x:y = 5} = {x: 10}; // 等同于 let y = 10
以及函数解构:
function test([x = 1, y = 2]) {
return x + y;
}
test([10]);
function test2(x, y) {
x = x || 1;
y = y || 2;
return x + y;
}
test2(10);
function test3({x = 1, y = 2}){
return x + y;
}
test3({x: 10})