重复字符串 - Javascript [英] Repeat String - Javascript

查看:155
本文介绍了重复字符串 - 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('');
}


推荐答案


新读者注意事项:这个答案很老,而且不太实用 - 它只是聪明,因为它使用数组的东西来获得
String完成的事情。当我写less process时,我绝对意味着
更少代码,因为正如其他人在后续回答中所指出的那样,
就像猪一样。因此,如果速度对您很重要,请不要使用它。

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. 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.

我将此函数直接放在String对象上。而不是创建一个数组,填充它,并用空char连接它,只需创建一个适当长度的数组,并将其与您想要的字符串连接。相同的结果,更少的过程!

I'd put this function onto the String object directly. 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\n".repeat( 4 ) );

这篇关于重复字符串 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆