如何在JavaScript中重复字符串? [英] How can I repeat strings in JavaScript?

查看:163
本文介绍了如何在JavaScript中重复字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我如何创建重复字符串的字符串x次:

In JavaScript, how would I create a string of repeating strings x number of times:

var s = new String(" ",3);

//s would now be "   "


推荐答案

没有这样的功能,但是,嘿,你可以创建它:

There is no such function, but hey, you can create it:

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

用法:

var s = " ".repeat(3);

当然,您可以将其作为独立功能组的一部分来编写:

Of course you could write this as part of a standalone group of functions:

var StringUtilities = {
    repeat: function(str, times) { 
       return (new Array(times + 1)).join(str);
    }
    //other related string functions...
};

用法:

var s = StringUtilities.repeat(" ", 3);

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

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