我一直在尝试从 Object.assign 的父赋值中分配嵌套在对象中的许多值。我让它按照我想要的方式工作。但是,我不知道它是如何或为何起作用的。为什么需要在第二个 Object.assign 计算 style 之前计算它?
var cards = Object.assign(card=document.createElement('div'),style=card.style, {
id:'cards',
innerHTML:'hello world',
[style]:[Object.assign(style,{
width:"300px",
margin:'auto',
color:'green',
height:'300px',
})]
});
var body= document.querySelector('body');
body.appendChild(cards);
最佳答案
该代码不会执行您想要的操作,并且不会按照您想象的方式工作。请注意,您是 accidentally introducing global variables ,并且您计算出的属性键将是无用且未使用的 "[object CSSStyleDeclaration]"
。它确实达到了预期的效果,因为 Object.assign(style, …)
已被评估,但在嵌套对象中执行它没有任何影响。
你应该这样写
var card = document.createElement('div');
Object.assign(card, {
id:'cards',
innerHTML:'hello world'
});
var style = card.style;
Object.assign(style, {
width:"300px",
margin:'auto',
color:'green',
height:'300px',
});
var body = document.querySelector('body');
body.appendChild(cards); // probably not necessary, cards already is part of the document
或者可能更简单
var card = document.createElement('div');
card.id = 'cards';
card.innerHTML = 'hello world';
var style = card.style;
style.width = "300px";
style.margin = 'auto';
style.color = 'green';
style.height = '300px';
<小时/>
当我们对 Object.assign
进行脱糖时,也许有助于了解您做错了什么。您的代码相当于
_temp1 = card=document.createElement('div'); // global variable!
_temp2 = style=card.style; // global variable!
_temp3 = {
id:'cards',
innerHTML:'hello world'
};
_temp4 = style;
_temp5 = {
width:"300px",
margin:'auto',
color:'green',
height:'300px',
};
for (p in _temp5) // the Object.assign(style, {…})
_temp4[p] = _temp5[p];
_temp3[String(style)] = [_temp4]; // WTF
for (p in _temp2) // the first part of Object.assign(card, style, …)
_temp1[p] = _temp2[p]; // WTF
for (p in _temp3) // the second part of Object.assign(card, …, {…})
_temp1[p] = _temp3[p];
var cards = _temp1;
var body = document.querySelector('body');
body.appendChild(cards);
关于javascript - 通过 Object.assign 中的父赋值来分配嵌套在对象中的许多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44320573/