ES6/ES2015 对象解构和改变目标变量 [英] ES6/ES2015 object destructuring and changing target variable

查看:35
本文介绍了ES6/ES2015 对象解构和改变目标变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在对象销毁过程中重命名目标?

How can I rename the target during object destructing?

const b = 6;
const test = { a: 1, b: 2 };
const {a, b as c} = test; // <-- `as` does not seem to be valid in ES6/ES2015
// a === 1
// b === 6
// c === 2

推荐答案

您可以分配新的变量名称,例如 MDN 示例

You can assign new variable names, like shown in this MDN Example

var o = { p: 42, q: true };

// Assign new variable names
var { p: foo, q: bar } = o;

console.log(foo); // 42
console.log(bar); // true  

所以,在你的情况下,代码将是这样的

So, in your case, the code will be like this

const b = 6;
const test = { a: 1, b: 2 };
let { a, b: c } = test;
console.log(a, b, c); // 1 6 2

在线 Babel 演示

这篇关于ES6/ES2015 对象解构和改变目标变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆