开发者

Does Javascript support the short ternary (rather, variation of) as in PHP?

I've become fond of PHP's support for the "short ternary", omitting the second expression:

// PHP

$foo = 'hello';
$bar = '';

echo $foo ?: 'world'; // hello
echo $bar ?: 'world'; // world

Does Javascript support any sort of syntax like this? I've tried ?: resulting in a syntax error. I'm aware of boolean short circuits, but that's not feasible for what I'm currently doing; that being:

// Javascript

var data = {
    key: value ?: 'default'
};

Any suggestions? (I could wrap it in an imme开发者_如何学编程diately invoked anonymous function, but that seems silly)


var data = {
    key: value || 'default'
};


Yes, use ||. Unlike PHP, JavaScript's || operator will return the first non-falsy value, not a normalized boolean.

foo || 'world'


var myFunc = function(foo) {
  foo = foo || 'my default value for foo';
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜