js:重复输出字符串中字符

复习了 重复输出一个字符串后,

重复输出一个字符串是

比如给定 str:abc  num:3

要求输出 abcabcabc

文章链接:https://www.cnblogs.com/mobu/p/9899062.html

之后,我研究起了 重复输出字符串中字符

比如给定 str:abc  num:3

要求输出 aaabbbccc

除了对字符串迭代的方法,剩下的方法相当于把字符串分成数组,然后再用上一个方法输出

/******************************************
abc --> aaabbccc
*******************************************/

var times = (str, num) => str.split('').map(e => e.repeat(num)).join('');
console.log('1', times('abc', 3));
console.log('一句代码:', ((str, num) => str.split('').map(e => e.repeat(num)).join(''))('abc', 3));

var times = (str, num) => str.split('').map(e => new Array(num + 1).join(e)).join('');
console.log('2', times('abc', 3));

var times = (str, num) => str.split('').map(e => Math.pow(10, num - 1).toString().replace(/1|0/g, e)).join('');
console.log('3', times('abc', 3));

// 遍历到遍历+三元函数
var times = (str, num) => {
    var ss = ''
    var len = str.length

    function tt(len) {
        return --len >= 0 ? ss = tt(len) + str[len].repeat(num) : ''
    }
    return tt(len)
}
console.log('4', times('abc', 3));

var times = (str, num, len = str.length, ss = '') => {
    return --len >= 0 ? ss = times(str, num, len, ss) + str[len].repeat(num) : ''
}
console.log('5', times('abc', 3));

猜你喜欢

转载自www.cnblogs.com/mobu/p/10468482.html