【问题标题】:conditional variable in object对象中的条件变量
【发布时间】:2012-10-27 22:07:04
【问题描述】:

刚刚尝试做这样的事情,它不会工作,想知道是否还有?

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

这是由于conditional 中存在: 而导致的。无论如何要做到这一点,而不会破坏并保持obj的这种格式。

我知道我能做到。

obj.conditional = (something) ? "something" : "nothing";

【问题讨论】:

  • 我的代码与上面的示例不同,并且缺少括号。

标签: javascript object shorthand conditional


【解决方案1】:

使用另一组括号?

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

只需要让解析器知道要注意哪个: 以及用于什么目的。

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

如果需要在参考时做出决定,您也可以使用function(){}。例如

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'

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多