zoukankan      html  css  js  c++  java
  • 封装个StringBuffer,用array join的方式拼接字符串

     1 (function(window) {
     2     var core_ArrPro = Array.prototype;
     3     var core_slice = core_ArrPro.slice;
     4     var core_push = core_ArrPro.push;
     5     var core_unshift = core_ArrPro.unshift;
     6 
     7     function StringBuffer() {
     8         this.buffer = [];
     9     }
    10     StringBuffer.prototype = {
    11         push: function() {
    12             core_push.apply(this.buffer, core_slice.call(arguments));
    13             return this;
    14         },
    15         unshift: function() {
    16             core_unshift.apply(this.buffer, core_slice.call(arguments));
    17             return this;
    18         },
    19         toString: function() {
    20             return this.buffer.join('');
    21         }
    22     };
    23     return window.StringBuffer = StringBuffer;
    24 })(window);
    25 document.getElementById('result').innerHTML = new StringBuffer().push('asdasd').unshift('654', 123).push(123, 564, 'sdf');

     由于apply效率低于call,而大多push操作只有1个参数,随更新为如下:

    (function(window) {
                    var core_ArrPro = Array.prototype;
                    var core_slice = core_ArrPro.slice;
    
                    function StringBuffer() {
                        this.buffer = [];
                    }
                    StringBuffer.prototype = {
                        push: function() {
                            if(arguments.length == 1){
                                this.buffer.push(arguments[0])
                            }else if(arguments.length > 1){
                                this.buffer = this.buffer.concat(core_slice.call(arguments));
                            }
                            return this;
                        },
                        unshift: function() {
                            if(arguments.length == 1){
                                this.buffer.unshift(arguments[0])
                            }else if(arguments.length > 1){
                                this.buffer = core_slice.call(arguments).concat(this.buffer)
                            }
                            return this;
                        },
                        toString: function() {
                            return this.buffer.join('');
                        }
                    };
                    return window.StringBuffer = StringBuffer;
                })(window);
                document.getElementById('result').innerHTML = new StringBuffer().push('asdasd').unshift('654', 123).push(123, 564, 'sdf');
  • 相关阅读:
    php xml解析方法
    phpmail 发送邮件失败
    善用Eclipse的代码模板功能
    php5.3 namespace
    MyEclipse6.5配置反编译插件
    程序bug致损失400亿,判程序员坐牢? 搞笑我们是认真的
    ios学习笔记(二)第一个应用程序--Hello World
    ios学习笔记(一)Windows7上使用VMWare搭建iPhone开发环境
    GJB150-2009军用装备实验室环境试验方法新版标准
    AXI总线简介
  • 原文地址:https://www.cnblogs.com/henryli/p/3644813.html
Copyright © 2011-2022 走看看