zoukankan      html  css  js  c++  java
  • 重复输出字符串

    重复输出字符串

    在 String 对象上定义一个 repeatify 函数。这个函数接受一个整数参数,来明确字符串需要重复几次。这个函数要求字符串重复指定的次数。

    所有的字符串的方法应该添加到String函数构造出的所有字符串上,首先应当判断是否已经有了这个方法,没有则添加。

    最简单的循环方式:

    String.prototype.repeatify = String.prototype.repeatify || function(times){
        var str = '';
        //判断是否正整数
        if(times>0){
            if(typeof times === 'number'&&times%1 === 0){
                for (var i = 0; i < times; i++) {
                    str += this;
                }
                return str;
            }
        }else{
            console.log('参数错误')
            return '';
        }
    };
    console.log('asd'.repeatify(3.1))
    

    ,以下省略判断正整数,

    while循环模式:

    String.prototype.repeatify = String.prototype.repeatify || function(times){
        var str = '';
        while (time>0) {
            str += this;
            time--;
        }
        return str;
    };
    console.log('asd'.repeatify(3))//'asdasdasd'    
    

    拼接字符串可以使用join方法

            var str = [];
            while (times>0) {
                str.push(this);
                times--;
            }
            return str.join('');
    

    递归也可以达到效果:

    String.prototype.repeatify = String.prototype.repeatify || function(times){
        var str = '';
        if(times === 0){
            console.log
            return ''
        }else{
            if(times === 1){
                return this ;
            }else{
                return this + this.repeatify(times-1)
            }
        }
    };
    console.log('asd'.repeatify(3))//'asdasdasd'  
    

    es6中String有repeat方法,接受一个[0,无穷)的整数

    String.prototype.repeatify = String.prototype.repeatify || function(times){
       return times>0?this.repeat(times):''
    };
    console.log('asd'.repeatify(3))//'asdasdasd' 
    

    使用array的fill方法也可以(省略判断)

     return new Array(times).fill(this).join('');  
    

    或者直接join数组

     return new Array(times+1).join(this);
  • 相关阅读:
    file_put_contents 和php://input 实现存储数据进图片中
    Oracle PL/SQL游标的学习
    三层的再理解
    取出字符串中任意的顺序匹配
    oracle的正则表达式(regular expression)简单介绍
    oracle动态游标的简单实现方法
    存储过程之游标笔记小结
    char,varchar,nvarchar的区别
    大连惊魂记
    让asp.net默认的上传组件支持进度条反映(转)
  • 原文地址:https://www.cnblogs.com/mydia/p/6675767.html
Copyright © 2011-2022 走看看