【发布时间】:2017-06-03 22:01:06
【问题描述】:
我试图弄清楚为什么当其中一个是 HTML 元素时我不能合并 2 个或更多对象。
编辑:
为什么当我与Object.assign 2 个“普通”对象(如obj1 和obj2)合并时,我会从 obj2 的公共属性中获取值,但是当我对 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>
【问题讨论】:
-
您是否希望将
"i am obj1"和"i am obj2"连接起来? -
不,我希望得到一个新对象,而
id和textContent属性将从root对象中获取它们的值,作为传递给Object.assign的最后一个参数。
标签: javascript dom ecmascript-6