javascriptはstrigbufferの操作を実現します.
1665 ワード
function StringBuffer(){
if(this instanceof StringBuffer){
this.arr = [];
this.length = 0;
this.add = this.append = function(v){
if(v!==null&&v!==undefined){
var vt = v.toString();
this.length += vt.length;
this.arr.push(vt);
}
return this;
};
this.clear = this.empty = function(){
this.arr = [];
this.length = 0;
return this;
};
this.valueOf = this.toString = function(v){
if(!!v){
return this.arr.join(v);
}else{
return this.arr.join("");
}
};
this.substring = function(){
return this.valueOf().substring(arguments[0],arguments[1]);
};
this.removeLast = function(){
if(this.length>0){
var tmp = this.arr[this.arr.length-1].toString();
if(tmp.length==1){
this.arr.pop();
}else{
this.arr[this.arr.length-1] = tmp.substring(0, tmp.length-1);
}
this.length -= 1;
}
return this;
};
this.removeLastAppend = this.removeLastAdd = function(){
if(this.length>0){
var s = this.arr.pop();
this.length -= s.length;
}
return this;
};
this.charAt = function(index){
if(typeof index!=="number"){
throw new Error("\u671f\u671b\u662f\u6570\u5b57\u7c7b\u578b\uff0c\u7ed3\u679c\u662f\u5176\u4ed6\u7c7b\u578b!");
}
return this.valueOf().charAt(index);
}
this.replace = function(start, end, str){
if(start>=end) throw new Error("\u53c2\u6570\u6709\u8bef"); //
var tmp = this.valueOf();
tmp = tmp.substring(0, start)+str+tmp.substring(end);
this.empty().append(tmp);
return this;
}
}else{
return new StringBuffer();
}
};