1

让我有部分用户地址应该格式化为单个字符串。
地址组件是

Street  
City  
Phone  
State  
Zip  

并且应该格式化为 string street city, phone, state zip。(2 个逗号)。
问题是每个领域都可以null。所以如果street == nullcity == 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
  }
4

4 回答 4

5
var fields = [[address.street, address.city], [address.phone], [address.state, address.zip]];
return fields.map(function(part) {
    return part.filter(Boolean).join(" ");
}).filter(function(str) { return str.length; }).join(", ");

或者,在没有filterand的循环中map,但是将属性名称映射到它们的值:

var fields = [["street", "city"], ["phone"], ["state", "zip"]];
for (var strs=[], i=0; i<fields.length; i++) {
    for (var parts=[], j=0; j<fields[i].length; j++)
        if (address[fields[i][j]])
            parts.push(address[fields[i][j]]);
    if (parts.length)
        strs.push(parts.join(" "));
}
return strs.join(", ");
于 2012-10-25T14:43:13.037 回答
1

将其添加到数组并删除一些相邻的逗号和空格。

var street = "street";
var city = "city";
var phone = "phone";
var state = "state";
var zip = "zip";
[
    street,
    city, ",",
    phone, ",",
    state,
    zip
].join(" ") //add all items with spaces in between
.replace(/(\s*,\s*)+/g, ", ") //remove multiple spaces before or after commas
.replace(/\s+/g, " "); //remove any other double spaces
于 2012-10-25T14:38:46.130 回答
0

可以通过以下功能更清洁:

function formatAddressPart(part,concatString){
     return part ? part+concatString : "";
}


var formatAddress = function(address) {
     var retVal = ""

     if (address.street || address.city)
     {
        retVal += formatAddressPart(address.street, " ");
        retVal += formatAddressPart(address.city,""); 
        retVal += ", ";
     }
     retVal += formatAddressPart(address.phone,", ");

     retVal += formatAddressPart(address.state," ");
     retVal += formatAddressPart(address.zip,"");  

     return retVal
  }
于 2012-10-25T14:37:15.323 回答
0

将您的字符串放入一个数组中,然后使用 join 方法并使用单个逗号删除多个连续逗号

a = [address.Street, 
     address.City, 
     address.Phone, 
     address.State, 
     address.Zip].join (', ').replace (/(, ){2,}/g, ', ');
于 2012-10-25T15:09:35.107 回答