Create a StringBuffer class based on array in JavaScript

Description

The following code shows how to create a StringBuffer class based on array.

Example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function StringBuffer() {<!-- w w  w .  j ava2  s.  c o m-->
this.__strings__ = new Array;
}

StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};

StringBuffer.prototype.toString = function () {
return this.__strings__.join("");
};

var buffer = new StringBuffer();

for (var i=0; i < 100; i++) {
buffer.append("text");
}
var result = buffer.toString();


document.write(result.length());
</script>
</head>
<body>
</body>
</html>

Click to view the demo

The code above generates the following result.

Create a StringBuffer class based on array in JavaScript