让我有部分用户地址应该格式化为单个字符串。
地址组件是
Street
City
Phone
State
Zip
并且应该格式化为 string street city, phone, state zip
。(2 个逗号)。
问题是每个领域都可以null
。所以如果street == null
和city == null
,那么我应该有字符串phone, state zip
(1个逗号)。问题在于控制空格数和逗号数
如何避免和最小化空检查的数量?
我目前的代码是
var formatAddress = function(address) {
var retVal = ""
if (address.street || address.city)
{
retVal += address.street ? address.street + " " : ""
retVal += address.city ? address.city : ""
retVal += ", ";
}
retVal += address.phone ? address.phone + ", " : ""
retVal += address.state ? address.state : ""
retVal += address.zip ? " " + address.zip : ""
return retVal
}