JavaScript简写三元运算符 [英] JavaScript shorthand ternary operator
本文介绍了JavaScript简写三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在PHP 5.3中,而不是使用这种冗余的三元运算符语法:
I know that in PHP 5.3 instead of using this redundant ternary operator syntax:
startingNum = startingNum ? startingNum : 1
...我们可以在适用的情况下为三元运算符使用简写语法:
...we can use a shorthand syntax for our ternary operators where applicable:
startingNum = startingNum ?: 1
我知道JavaScript中的三元运算符:
And I know about the ternary operator in JavaScript:
startingNum = startingNum ? startingNum : 1
...但是有速记吗?
...but is there a shorthand?
推荐答案
var startingNumber = startingNumber || 1;
类似您要查找的内容,如果未定义则默认为默认值?
Something like that what you're looking for, where it defaults if undefined?
var foo = bar || 1; // 1
var bar = 2;
foo = bar || 1; // 2
顺便说一下,这适用于很多场景,包括对象:
By the way, this works for a lot of scenarios, including objects:
var foo = bar || {}; // secure an object is assigned when bar is absent
这篇关于JavaScript简写三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文