ITeye博客

定义JavaScript中的StringBuffer类

zwfc · 2008-12-25 13:29 · Markdown

  1. //StringBuffer类定义
  2. functionStringBuffer(){
  3. this._strings=newArray;
  4. }
  5. StringBuffer.prototype.append=function(str){
  6. this._strings.push(str);
  7. };
  8. StringBuffer.prototype.toString=function(){
  9. returnthis._strings.join(“”);
  10. };
  11. //test
  12. varbuffer=newStringBuffer();
  13. buffer.append(“hello“);
  14. buffer.append(“world”);
  15. varresult=buffer.toString();

使用StringBuffer拼接字符串比用String效率高。

考虑下面一段代码的运行。

var str = “hello “;
str += “world”;
This code actually executes the following steps behind the scenes:
1. Create a string to store “hello “.
2. Create a string to store “world”.
3. Create a string to store the result of concatenation.
4. Copy the current contents of str into the result.
5. Copy the “world” into the result.
6. Update str to point to the result.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。