javascript模拟 C#中的StringBuilder,提升JS中字符串拼接的效率及性能

来源:互联网 发布:光盘制作软件 编辑:程序博客网 时间:2024/05/29 10:41

/*利用Array对象join方法模拟 C#中的StringBuilder,提升JS中字符串拼接的效率及性能。功能同JS文件夹下StringBuilder.js文件实现功能,因实现方式不同且为避免冲突将此文件置于该文件夹下供月度资金计划使用Author : panwb Date   : 2012-11-29*/function StringBuilder(str){    //字符串数组this.arrstr = (str === undefined ? new Array() : new Array(str.toString()));    //字符串长度(任何影响newstr字符串长度的方法都必须同时重置length)this.length = (str === undefined ? 0 : str.length);    // 字符串模板转换,类似于C#中的StringBuilder.Append方法this.append = StringBuilder_append;    // 字符串模板转换,类似于C#中的StringBuilder.AppendFormat方法this.appendFormat = StringBuilder_appendFormat;    //重写toString()方法this.toString = StringBuilder_toString;    //重写replace()方法this.replace = StringBuilder_replace;    //添加remove()方法this.remove = StringBuilder_remove;    //从当前实例中移除所有字符    this.clear = StringBuilder_clear;}// 字符串模板转换,类似于C#中的StringBuilder.Append方法function StringBuilder_append(f){    if (f === undefined || f === null)    {        return this;    }    this.arrstr.push(f);    this.length += f.length;    return this;}// 字符串模板转换,类似于C#中的StringBuilder.AppendFormat方法function StringBuilder_appendFormat(f){    if (f === undefined || f === null)    {        return this;    }    //存储参数,避免replace回调函数中无法获取调用该方法传过来的参数    var params = arguments;        var newstr = f.toString().replace(/\{(\d+)\}/g,        function (i, h) { return params[parseInt(h, 10) + 1]; });    this.arrstr.push(newstr);    this.length += newstr.length;    return this;}//重写toString()方法function StringBuilder_toString(){    return this.arrstr.join('');}//重新replace()方法function StringBuilder_replace(){    if (arguments.length >= 1)    {        var newstr = this.arrstr.join('').replace(arguments[0], arguments[1]);        this.arrstr.length = 0;        this.length = newstr.length;        this.arrstr.push(newstr);    }    return this;}//添加remove()方法function StringBuilder_remove(){    if (arguments.length > 0)    {        var oldstr = this.arrstr.join('');        var substr = (arguments.length >= 2 ?            oldstr.substring(arguments[0], arguments[1]) : oldstr.substring(arguments[0]));        var newstr = oldstr.replace(substr, "");        this.arrstr.length = 0;        this.length = newstr.length;        this.arrstr.push(newstr);    }    return this;}//从当前实例中移除所有字符function StringBuilder_clear(){    this.arrstr.length = 0;    this.length = 0;    return this;}




欢迎提出您宝贵的意见一起讨论改进!