开发者

Declare an object with keys being assigned value of other keys?

开发者 https://www.devze.com 2023-02-04 14:40 出处:网络
Is there a better title for this? Okay, is something like this legal? var myobj = { key1: \"val开发者_如何学编程1\",

Is there a better title for this?

Okay, is something like this legal?

var myobj = {
    key1: "val开发者_如何学编程1",
    key2: this.key1
};

I haven't tried it, but I'm looking for a way to have identical values for separate keys in an object, preferably in a concise way.


Your code is legal but doesn't do what you mean. When evaluating the key:... part this is not bound to the yet-non-existent object, but to the context where myobj is being built. You have to store the value in a variable and then using the variable... like:

var kv = "val1";
var myobj = {
    key1: kv,
    key2: kv
};

note that here you're not creating a closure if this is your fear. That only happens for function expressions


try:

var myobj = {};
myobj['key2'] = (myobj['key1'] = 'val1');

Since in javascript, value assignment also returns the value as well, so you can be somewhat concise.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号