是否有任何语法可以执行以下操作
var obj = {a: this, b: this}
并获取
obj = {a: 'a', b: 'b'}
答案 0 :(得分:1)
你可以这样做:
var obj = {a: "this is A", b: "this is B"}
obj.a equals to "this is A"
obj.b equals to "this is B"
使用此对象示例添加存储在对象中的指针位置的快速代码段:
function getMousePosition(event){
var mouse = {x: 0, y: 0};
mouse.x = event.clientX;
mouse.y = event.clientY;
Elem = document.getElementById("Elem");
Elem.innerHTML = "Simple Mouse Position by Khriztian Azuaje.<br><br>" + "X pos: " + mouse.x + ", Y pos: " + mouse.y;
}
&#13;
#Elem {
background:black;
text-align: center;
color:white;
padding:2px;
display: flex;
align-items: center;
justify-content: center;
height:160px;
}
&#13;
<body onmousemove="getMousePosition(event)">
<div id="Elem"></div>
</body>
&#13;
答案 1 :(得分:1)
如果你想创建一个具有一堆键和值等于相同字符串的对象,它就像这样简单:
var obj = {};
['a','b'].forEach(function(item) {
obj[item] = item;
});
答案 2 :(得分:1)
是的!我不确定你为什么要使用但是在这里:
var obj = { a: 'you', b: 'they'};
var newObj = {};
for (var key in obj) {
newObj[key] = key
};
//newObj = {a: "a", b: "b"}