JavaScript StringBuilder

本文介绍了一种使用自定义StringBuilder类进行字符串拼接的方法。通过创建StringBuilder实例并调用其append方法来添加文本片段,最后将所有片段转换为完整的字符串。这种方式在处理大量字符串拼接时比直接使用加号更高效。
ContractedBlock.gifExpandedBlockStart.gifCode
// 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("");
}
ContractedBlock.gifExpandedBlockStart.gifCode
// create a StringBuilder
var sb = new StringBuilder();

// append some text
sb.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, ");
sb.append(
"sed diem nonummy nibh euismod tincidunt ut lacreet dolore ");
sb.append(
"magna aliguam erat volutpat.");

// get the full string value
var s = sb.toString();

转载于:https://www.cnblogs.com/joe-yang/archive/2008/11/30/1344419.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值