Jua*_*edo 3 javascript destructuring ecmascript-6 object-destructuring
我正在尝试使用对象解构来提取变量,但这些变量已经存在,就像这样
const x=1, y=2 // Those should be 1 and 2
const {x,y} = complexPoint
const point = {x,y}
Run Code Online (Sandbox Code Playgroud)
有没有办法在不重命名解构变量的情况下做到这一点?有些人喜欢这样并更新点避免const定义?
const point = {x,y} = complexPoint
Run Code Online (Sandbox Code Playgroud)
预期的结果应该是使用对象解构
const x=1, y=2 // Those should be 1 and 2
const point = {
x:complexPoint.x,
y:complexPoint.y
}
Run Code Online (Sandbox Code Playgroud)
你可以用数组解构来做到这一点,即:
const complexPoint = [1,2];
let x, y;
[x,y] = complexPoint;
Run Code Online (Sandbox Code Playgroud)
至于对象解构,等效的语法将不起作用,因为它会抛弃解释器:
const complexPoint = {x:1,y:2};
let x, y;
{x,y} = complexPoint; // THIS WOULD NOT WORK
Run Code Online (Sandbox Code Playgroud)
解决方法可能是:
const complexPoint = {x:1,y:2};
let x, y;
[x,y] = [complexPoint.x, complexPoint.y];
// Or
[x,y] = Object.values(complexPoint);
Run Code Online (Sandbox Code Playgroud)
更新:
看来您可以通过将赋值括在括号中并将其转换为表达式来将对象分解为现有变量。所以这应该有效:
const complexPoint = {x:1,y:2};
let x, y;
({x,y} = complexPoint); // THIS WILL WORK
Run Code Online (Sandbox Code Playgroud)
这里可以这样做。
const complexPoint = {x: 1, y: 2, z: 3};
const simplePoint = ({x, y}) => ({x, y});
const point = simplePoint(complexPoint);
console.log(point);Run Code Online (Sandbox Code Playgroud)
在一行中看起来像这样:
const complexPoint = {x: 1, y: 2, z: 3};
// can be written as
const point2 = (({x, y}) => ({x, y}))(complexPoint);
console.log(point2);Run Code Online (Sandbox Code Playgroud)