Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - 重复字符串-Javascript(Repeat String - Javascript)

What is the best or most concise method for returning a string repeated an arbitrary amount of times?

(返回任意多次重复的字符串的最佳或最简洁的方法是什么?)

The following is my best shot so far:

(以下是到目前为止我最好的拍摄:)

function repeat(s, n){
    var a = [];
    while(a.length < n){
        a.push(s);
    }
    return a.join('');
}
  ask by brad translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note to new readers: This answer is old and and not terribly practical - it's just "clever" because it uses Array stuff to get String things done.

(给新读者的注意:这个答案是旧的,并且不是很实用-它只是“聪明”,因为它使用Array的东西来完成String的工作。)

When I wrote "less process" I definitely meant "less code" because, as others have noted in subsequent answers, it performs like a pig.

(当我写“更少的过程”时,我的意思绝对是“更少的代码”,因为正如其他人在随后的答案中指出的那样,它的表现像猪一样。)

So don't use it if speed matters to you.

(因此,如果速度对您很重要,请不要使用它。)

I'd put this function onto the String object directly.

(我直接将此函数放到String对象上。)

Instead of creating an array, filling it, and joining it with an empty char, just create an array of the proper length, and join it with your desired string.

(无需创建数组,填充数组并将其与空字符连接,只需创建适当长度的数组,然后将其与所需的字符串连接即可。)

Same result, less process!

(结果相同,过程更少!)

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

alert( "string to repeat
".repeat( 4 ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...