看下面的代码:
let method ='method1';
let headers ='headers1';
let body='body1';
const options = {};
options.method = method;
options.headers = headers;
options.body = body;
有没有觉得这样赋值挺麻烦的,其实ES6下有更方便的方法:
let method ='method1';
let headers ='headers1';
let body='body1';
const options = { method, headers, body };
console.log(options);
打印结果:
{method: "method1", headers: "headers1", body: "body1"}
如果要反过来呢:
let options={method: "method1", headers: "headers1", body: "body1"};
let { method, headers, body } = options;
console.log(method, headers, body);
打印结果:method1 headers1 body1
这叫解构赋值,类似的还有:
var first = someArray[0];
var second = someArray[1];
var third = someArray[2];
可以转换成:
var [first, second, third] = someArray;
网友评论