初步探究ES6之解构

738人阅读 评论(0)

语法

var first = someArray[0];
var second = someArray[1];
var third = someArray[2];


var [first, second, third] = someArray;

[ variable1, variable2, ..., variableN ] = array;

var [ variable1, variable2, ..., variableN ] = array;
let [ variable1, variable2, ..., variableN ] = array;
const [ variable1, variable2, ..., variableN ] = array;


var [foo, [[bar], baz]] = [1, [[2], 3]];
console.log(foo);
// 1
console.log(bar);
// 2
console.log(baz);
// 3


var [head, ...tail] = [1, 2, 3, 4];
console.log(tail);
// [2, 3, 4]
var [,,third] = ["foo", "bar", "baz"];
console.log(third);
// "baz"


function* fibs() {
var a = 0;
var b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}

var [first, second, third, fourth, fifth, sixth] = fibs();
console.log(sixth);
// 5


var robotA = { name: "Bender" };
var robotB = { name: "Flexo" };

var { name: nameA } = robotA;
var { name: nameB } = robotB;

console.log(nameA);
// "Bender"
console.log(nameB);
// "Flexo"

var { foo, bar } = { foo: "lorem", bar: "ipsum" };
console.log(foo);
// "lorem"
console.log(bar);
// "ipsum"

var complicatedObj = {
arrayProp: [
"Zapp",
{ second: "Brannigan" }
]
};

var { arrayProp: [first, { second }] } = complicatedObj;

console.log(first);
// "Zapp"
console.log(second);
// "Brannigan"


var [missing = true] = [];
console.log(missing);
// true

var { message: msg = "Something went wrong" } = {};
console.log(msg);
// "Something went wrong"

var { x = 3 } = {};
console.log(x);
// 3


应用

function removeBreakpoint({ url, line, column }) {
// ...
}


jQuery.ajax = function (url, {
async = true,
beforeSend = noop,
cache = true,
complete = noop,
crossDomain = false,
global = true,
// ... more config
}) {
// ... do stuff
};


var map = new Map();
map.set(window, "the global");
map.set(document, "the document");

for (var [key, value] of map) {
console.log(key + " is " + value);
}
// "[object Window] is the global"
// "[object HTMLDocument] is the document"

for (var [key] of map) {
// ...
}
for (var [,value] of map) {
// ...
}


2
0

个人主页
个人资料
• 访问：311721次
• 积分：4627
• 等级：
• 排名：第7504名
• 原创：146篇
• 转载：0篇
• 译文：0篇
• 评论：86条
博客专栏
 数据结构的javascript描述 文章：39篇 阅读：32135
 深入理解javascript 文章：17篇 阅读：26218