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

问题描述 投票:0回答:2

我正在尝试分解对象,但是那些变量已经存在,像这样

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
javascript ecmascript-6 destructuring object-destructuring
2个回答
0
投票

您可以使用闭包将结构分解为现有变量:

const complexPoint = { x: 1, y: 2, z: 3 }
let x,y
({x,y} = complexPoint)
const point = {x,y}

console.log(point)

0
投票

这里可以这样做。

const complexPoint = {x: 1, y: 2, z: 3};
const simplePoint = ({x, y}) => ({x, y});

const point = simplePoint(complexPoint);

console.log(point);

// can be written as
const point2 = (({x, y}) => ({x, y}))(complexPoint);

console.log(point2);
© www.soinside.com 2019 - 2024. All rights reserved.