JavaScript:生成重复的字符串(字符串乘法)

更新日期: 2018-11-03阅读: 4.1k标签: js

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

比如str:bac     num:3
输出:abcabcabc


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

1. 递归,结合三元表达式更简洁。
2. 数组的  join() 方法。
3. ES6的 repeat() 方法。ES6目前没有全部兼容。

以下为三种方式代码:  


三元表达式+递归

function times(str, num){
        return num > 1 ? str += times(str, --num): str;
}
console.log(times('abc', 3));


数组方法

//   另外可用call()改变Array原型链上join()方法的对象并指向String
function times2(str, num){
        return new Array(num+1).join(str);
}
console.log(times2('abc', 3));


ES6 repeat()

function times3(str, num) {
        return num > 1 ? str.repeat(num): str;
}
console.log(times3('abc', 3));


来自:https://www.cnblogs.com/mobu/archive/2018/11/02/9899062.html


链接: https://www.fly63.com/article/detial/1255

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!