-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
[js] 第72天 写一个字符串重复的repeat函数 #511
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
|
@AnsonZnl 不错,还有别的方法吗? |
百度看到的哈哈 |
@AnsonZnl 也不错,还有别的方法吗? |
const repeat = (str, n)=>str.repeat(n) |
const repeat = (str,n)=>str.padEnd(((n+1)*str.length,str) |
const repeatStr = (str, num) => {
return Array(num + 1).fill(str).join('')
} |
|
const repeatStr = ({str = "", repeat = 1}) => {
if (!str || repeat === 0) {
return str;
}
return (str += repeatStr({str: str, repeat: (repeat -= 1)}));
};
console.log(repeatStr({str: "abc", repeat: 3}));
console.log(repeatStr({str: "abc_e", repeat: 2}));
console.log(repeatStr({str: "abc||", repeat: 4}));
console.log(repeatStr({str: "a b c_", repeat: 2}));
console.log(repeatStr({str: "_abc_", repeat: 3}));
console.log(repeatStr({str: "_abc_"})); |
时间复杂度:O(logN) const repeat = (str, count) => {
if (count === 0) {
return '';
}
if (count === 1) {
return str;
}
let result = repeat(str + str, count >> 1)
if (count & 1) {
result += str;
}
return result;
} |
let a = [...b , ...c].join() b或者c给一个空数组 菜鸡前端 方法有点偏门 不知道对不对 |
|
String.prototype.repeat = function (count) {
let originStr = String(this);
let thisStr = this;
for (let i = 1; i < count; i++) {
thisStr += originStr;
}
return thisStr
};
console.log("asd".repeat(2)); |
ES6本身提供了String实例的repeat方法,如果还要手写,一般是考虑兼容性问题,得用旧的语法
|
var str = "123"; console.log(test4()); function test1() { function test2() { function test3() { function test4() { |
function repeat(str,n) { |
|
String.prototype.myRepeat = function(){
const num = arguments[0]
const str = this.toString()
if(typeof num !== 'number'){
throw new Error('参数要为number类型')
}
let result = ''
if(num === 0){
result = ''
} else if( num > 0 && num !== Infinity ){
for(let i = 0;i < num ; i++){
result += str
}
} else {
throw new Error('请输入正确的参数')
}
return result
}
const str = 'repeat'
let newStr = str.myRepeat(5)
console.log(newStr) |
function repeat(str, num) {
|
第72天 写一个字符串重复的repeat函数
The text was updated successfully, but these errors were encountered: