是否可以在现有对象上进行解构?(Javascript ES6)

编程入门 行业动态 更新时间:2024-10-21 18:57:06
本文介绍了是否可以在现有对象上进行解构?(Javascript ES6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,如果我有两个对象:

For example if I have two objects:

var foo = { x: "bar", y: "baz" }

var oof = {}

我想将 x 和 y 值从 foo 转移到 oof.有没有办法使用 es6 解构语法来做到这一点?

and I wanted to transfer the x and y values from foo to oof. Is there a way to do that using the es6 destructuring syntax?

可能是这样的:

oof{x,y} = foo

推荐答案

虽然丑陋且有点重复,但你可以做到

While ugly and a bit repetitive, you can do

({x: oof.x, y: oof.y} = foo);

它将读取foo 对象的两个值,并将它们写入oof 对象上的各自位置.

which will read the two values of the foo object, and write them to their respective locations on the oof object.

我个人还是比较喜欢阅读

Personally I'd still rather read

oof.x = foo.x; oof.y = foo.y;

['x', 'y'].forEach(prop => oof[prop] = foo[prop]);

虽然.

更多推荐

是否可以在现有对象上进行解构?(Javascript ES6)

本文发布于:2023-10-31 04:20:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544983.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!