複製代碼 代碼如下:// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value)
{
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
{
if (value)
{
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function ()
{
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function ()
{
return this.strings.join("");
}
代碼看上去很簡單直接。實際上就是用array,push,join等來實現,以下是如何使用該類 複製代碼 代碼如下:// create a StringBuilder
var sb = new StringBuilder();
// append some text
sb.append("Some of those preparing for international ");
sb.append("exams such as the TOEFL ");
sb.append("need extra practice for the listening section");
// get the full string value
var s = sb.toString();
alert(s);
非常簡單,不需要太多的說明。如果你在.NET中用了StringBuilder,你也會知道這裡如何用。