实现js版StringBuilder
.net中StringBuilder的好处不多说了,下面是js版的StringBuilder
function StringBuilder() { this.__stringArr__ = []; } $.extend(StringBuilder.prototype, { append: function (str) { this.__stringArr__.push(str); }, appendFormat: function (str) { for (var i = 1,len=arguments.length; i < len; i++) { var reg = new RegExp("\\{"+(i-1)+"\\}","g"); str = str.replace(reg,arguments[i]); } this.__stringArr__.push(str); }, toString: function () { return this.__stringArr__.join(""); }, clear: function () { this.__stringArr__ = []; } });
调用:
var sb = new StringBuilder(); sb.append("1-"); sb.appendFormat("2:{0}", "hello"); console.info(sb.toString());