gpt4 book ai didi

javascript - 将 HTML 元素对象与自定义对象合并

转载 作者:行者123 更新时间:2023-11-29 21:05:24 26 4
gpt4 key购买 nike

我想弄清楚为什么当其中一个是 HTML 元素时我不能合并 2 个或更多对象。

编辑:
为什么当我与 Object.assign 2 个“普通”对象(如 obj1obj2 合并时,我从 obj2 获取公共(public)属性的值,但是当我对 root 做同样的事情,这是一个 HTML 元素我没有得到它的值(例如 id 属性的值)

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { id: "obj2", textContent: "i am obj2"};
const merged1 = Object.assign({}, obj1, obj2); // the new object got the id and textContent from obj2
const merged2 = Object.assign({}, obj1, root); // the new object got the id and textContent from obj1. why not from root?
console.log(merged1);
console.log(merged2);
console.log(root.id);
console.log(root.textContent);
<div id="root">i am root</div>

最佳答案

root 作为第一个参数传递给 Object.assign()

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"}
const merged = Object.assign(root, obj1, obj2);
console.log(merged);
console.log(root.id);
console.log(root.textContent);
<div id="root">i am root</div>

i don't want to override root, i want a new object and get the relevant values from the root object.

const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"};
const {id, textContent} = root;
const merged = Object.assign({}, obj1, obj2, {id, textContent});
console.log(merged);
console.log(root.id);
console.log(root.textContent);
<div id="root">i am root</div>

EDIT: Why when i merged with Object.assign 2 "normal" objects like obj1 and obj2 i get the values from obj2 on common properties, but when i do the same with root which is an HTML element i don't get its values (for example the value of id property)

Object.assign() 可以复制对象的可枚举属性。 HTMLDivElement idtextContent 属性不可枚举。

Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

const root = document.getElementById("root");
const props = ["textContent", "id"];

for (const prop of props) console.log(Object.propertyIsEnumerable(root, prop));
<div id="root">i am root</div>

关于javascript - 将 HTML 元素对象与自定义对象合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44348923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com