• 封装个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');
  • 相关阅读:
    Java中的并发库学习总结
    Android源码的git下载地址
    Android下载Android源码
    工具类 验证手机邮箱
    hibernate缓存说明
    Hibernate之N+1问题
    常用正则
    Java Base64加密、解密原理Java代码
    Base64加密解密原理以及代码实现(VC++)
    情书经典语录
  • 原文地址:https://www.cnblogs.com/henryli/p/3644813.html
Copyright © 2020-2023  润新知