Question

Just tried to do something like this and it wont work, wondering if there is anyway?

var obj = {
    intiger:5,
    conditional:(something) ? "something" : "nothing",
    string:"nothing important"
};

This is breaking because of the presence of the : within the conditional. Anyway to do this without it breaking and keeping this format of obj.

I know that I can do.

obj.conditional = (something) ? "something" : "nothing";
Était-ce utile?

La solution

Use another set of parenthesis?

...
conditional:((something)?"something":"nothing"),
...

Just have to let the parser know which : to pay attention to and for which purpose.

var foo = {
    bar: (true ? "true" : "false")
};
console.log(foo.bar); // true

You can also use a function(){} if the decision needs to be made at the time of reference. e.g.

var foo = {
    bar:function(){
        return this.baz == 'Brad' ? 'Me' : 'Not Me';
    },
    baz: 'Brad'
};
console.log(foo.bar()); // 'Me'
foo.baz = 'Thomas'; console.log(foo.bar()); // 'Not Me'
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top