现在的位置: 首页 > web前端 > 正文

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

2019年10月07日 web前端 ⁄ 共 1923字 ⁄ 字号 评论关闭
/*
利用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;
}

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

抱歉!评论已关闭.