实现js版StringBuilder

.net中StringBuilder的好处不多说了,下面是js版的StringBuilder

 1         var StringBuilder = (function () {
 2 
 3             function StringBuilder() {
 4 
 5                 this._stringArr = [];
 6 
 7             };
 8 
 9             StringBuilder.prototype.append = function (str) {
10 
11                 this._stringArr.push(str);
12 
13             };
14 
15             StringBuilder.prototype.appendFormat = function (str) {
16 
17                 for (var i = 1, len = arguments.length; i < len; i++) {
18 
19                     var reg = new RegExp("\\{" + (i - 1) + "\\}", "g");
20 
21                     str = str.replace(reg, arguments[i]);
22 
23                 }
24 
25                 this._stringArr.push(str);
26 
27             };
28 
29             StringBuilder.prototype.toString = function () {
30 
31                 return this._stringArr.join("");
32 
33             };
34 
35             StringBuilder.prototype.clear = function () {
36 
37                 this._stringArr = [];
38 
39             };
40 
41             return StringBuilder;
42 
43         }
44 
45         )();
46 
47 ---------------------------------------------------
48 
49 var sb = new StringBuilder();
50 
51         sb.append("1-");
52 
53         sb.appendFormat("2:{0}", "hello");
54 
55         console.info(sb.toString());
56 
57  

 

你可能感兴趣的:(实现js版StringBuilder)