码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript:三种简便方法生成重复的字符串(字符串乘法)

时间:2018-11-03 02:17:26      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:题目   cal   col   原型链   验证   学习   time   turn   array   

 

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

比如str:bac     num:3

输出:abcabcabc

 

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

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

2. 数组的  join() 方法。

3. ES6的 repeat() 方法。ES6目前没有全部兼容。

 

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

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

以下为三种方式代码:

 1     //三元表达式+递归
 2     function times(str, num){
 3         return num > 1 ? str += times(str, --num): str;
 4     }
 5     console.log(times(‘abc‘, 3));
 6     
 7     //数组方法
 8     //   另外可用call()改变Array原型链上join()方法的对象并指向String
 9     function times2(str, num){
10         return new Array(num+1).join(str);
11     }
12     console.log(times2(‘abc‘, 3));
13     
14     //ES6 repeat()
15     function times3(str, num) {
16         return num > 1 ? str.repeat(num): str;
17     }
18     console.log(times3(‘abc‘, 3));

 

JavaScript:三种简便方法生成重复的字符串(字符串乘法)

标签:题目   cal   col   原型链   验证   学习   time   turn   array   

原文地址:https://www.cnblogs.com/mobu/p/9899062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!