gpt4 book ai didi

javascript - 如何在 JavaScript 中重复字符串?

转载 作者:行者123 更新时间:2023-12-03 03:29:50 26 4
gpt4 key购买 nike

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

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

//s would now be "   "

最佳答案

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

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

用法:

var s = " ".repeat(3);

当然,您可以将其编写为独立函数组的一部分:

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

用法:

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

关于javascript - 如何在 JavaScript 中重复字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com