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');
  • 相关阅读:
    python爬虫学习之MongoDB学习笔记
    python基础学习笔记
    基于python的turtle模块画国旗
    基于tkinter的gui编程基础学习笔记
    python爬虫实现各视频网站vip付费电影下载
    网页模板收藏
    python爬虫实战项目
    python爬取詹姆斯职业生涯数据并生成图标展示
    爬虫框架scrapy学习笔记
    基于python的OpenCV图像处理学习笔记
  • 原文地址:https://www.cnblogs.com/henryli/p/3644813.html
Copyright © 2011-2022 走看看