是否可以将对象解构为现有变量?

2024-01-23

我正在尝试使用对象解构来提取变量,但这些变量已经存在,如下所示

const x=1, y=2 // Those should be 1 and 2
const {x,y} = complexPoint
const point = {x,y}

有没有办法在不重命名解构变量的情况下做到这一点? 有些喜欢这样并避免更新点const定义?

const point = {x,y} = complexPoint

预期结果应该与使用对象解构相同

const x=1, y=2 // Those should be 1 and 2
const point = {
  x:complexPoint.x,
  y:complexPoint.y
}

您可以通过数组解构来做到这一点,即:

const complexPoint = [1,2];

let x, y;
[x,y] = complexPoint;

至于对象解构,等效语法将不起作用,因为它会抛出解释器:

const complexPoint = {x:1,y:2};

let x, y;
{x,y} = complexPoint; // THIS WOULD NOT WORK

解决方法可能是:

const complexPoint = {x:1,y:2};

let x, y;
[x,y] = [complexPoint.x, complexPoint.y];

// Or
[x,y] = Object.values(complexPoint);

UPDATE:

看来您可以通过将赋值包含在括号中并将其转换为表达式来将对象解构为现有变量。所以这应该有效:

const complexPoint = {x:1,y:2};

let x, y;
({x,y} = complexPoint); // THIS WILL WORK
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以将对象解构为现有变量? 的相关文章

随机推荐