JavaScript:一句代码输出重复字符串(字符串乘法)

 

看到一个题目要求写一个函数times,输出str重复num次的字符串。

比如str:bac     num:3

输出:abcabcabc

 

除了利用循环还有几种方法,我学习研究之后记下以下三种方法。

1. 递归,结合三元表达式更简洁。

2. 数组的  join() 方法。

3. ES6的 repeat() 方法。

-------新加入

4.string的replace()方法 ----原创的哇,明天去面试,复习的时候我自己想出来的

 

我最喜欢第一种,因为用的都是最基本的语法,没有调用其他方法。

除了第一种剩下都可以一句代码完成输出。

python可以 str*num ,最先误以为js也行,验证了。。。不行  Orz。。。

 我的github:swarz,欢迎给老弟我++星星

以下代码:(假设num有效)

/******************************************
  1. 最简洁 三元表达式 + 递归
*******************************************/
var times = (str, num) => {
    return num > 1 ? str += times(str, --num) : str;
}
console.log('1', times('abc', 3));

/******************************************
  2. ES6 repeat()
*******************************************/
var times2 = (str, num) => str.repeat(num);
console.log('2', times2('abc', 3));

/******************************************
  3. 数组方法 join()
*******************************************/
var times3 = (str, num) => new Array(num + 1).join(str);
console.log('3', times3('abc', 3));

/******************************************
  4. 数组方法 fill() join()
*******************************************/
var times4 = (str, num) => new Array(num).fill(str).join('');
console.log('4', times4('abc', 3));

/******************************************
    5. 用call()改变Array原型链上join()方法
    可惜么理解 用对象添加属性?
*******************************************/
var times5 = (str, num) => Array.prototype.join.call({length: ++num}, str);
console.log('5', times5('abc', 3));

/******************************************
  6.string.replace
*******************************************/
var times6 = (str, num) => Math.pow(10, num - 1).toString().replace(/1|0/g, str)
console.log('6', times6('abc', 3));


/*++++++++++++++++++++++++++++++++++++++++++
    必须用一句代码实现的话
    除了第一种,都可以用匿名函数立即执行实现
++++++++++++++++++++++++++++++++++++++++++*/
//例如:
console.log('e.g.1', ((str, num) => str.repeat(num))('abc', 3));
console.log('e.g.2', ((str, num) => new Array(num + 1).join(str))('abc', 3));

执行结果:

 

posted @ 2018-11-02 23:21  高崇乐  阅读(3373)  评论(0编辑  收藏  举报