今天用JS 寫了一個 類似於 C# 中的 StringBuilder 類, 可以在Javascript 中調用.用於處理大量的字串拼接等,使得代碼易讀,易於維護.
首先引入 StringBuilder.js
<script type="text/javascript" src="StringBuilder.js"></script>
然後便可以很方便的使用了:
基本用法:
var sb=new StringBuilder();
sb.Append("Hello");
sb.Append("World !");
var Result=sb.ToString();
用法二:
代碼
// sb.AppendFormat("{0}....{N}","a",...."N");
var sb2=new StringBuilder();
var a="西狐";
var b=21;
var c="男";
sb2.Append("welcome! ");
sb2.AppendFormat("我叫:{0},年齡:{1},性別:{2}",a,b,c);
用法三:
代碼
// sb.AppendFormat("{0}....{N}",Array);
var sb3=new StringBuilder();
//可與數組一一對應
var param=new Array();
param[0]="20";
param[1]="微風三級";
param[2]="東南風";
param[3]="陽光明媚";
param[4]=new Date().toLocaleDateString();
sb3.AppendFormat("今天:{4},溫度:{0},風力:{1},風向:{2},{3}",param);
完整的範例程式碼:
代碼
<html>
<head>
<title>JavaScript StringBuilder Demo</title>
<script type="text/javascript" src="StringBuilder.js"></script>
<script type="text/javascript">
//Created By hooyes
//基本用法
var sb=new StringBuilder();
sb.Append("Hello");
sb.Append("World !");
var Result=sb.ToString();
document.write(Result);
document.write("<hr />");
//用法二
// sb.AppendFormat("{0}....{N}","a",...."N");
var sb2=new StringBuilder();
var a="西狐";
var b=21;
var c="男";
sb2.Append("welcome! ");
sb2.AppendFormat("我叫:{0},年齡:{1},性別:{2}",a,b,c);
document.write(sb2.ToString());
document.write("<hr />");
//用法三
// sb.AppendFormat("{0}....{N}",Array);
var sb3=new StringBuilder();
//可與數組一一對應
var param=new Array();
param[0]="20";
param[1]="微風三級";
param[2]="東南風";
param[3]="陽光明媚";
param[4]=new Date().toLocaleDateString();
sb3.AppendFormat("今天:{4},溫度:{0},風力:{1},風向:{2},{3}",param);
document.write(sb3.ToString());
</script>
</head>
<body>
</body>
</html>
StringBuilder.js 代碼及樣本下載:
/Files/hooyes/jsStringBuilder.rar