返回一个重复任意次数的字符串的最佳或最简洁的方法是什么?
以下是我迄今为止的最佳镜头:
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
Run Code Online (Sandbox Code Playgroud) 我确实检查了其他问题; 这个问题的重点是以最有效的方式解决这个特定问题.
有时您希望创建一个具有指定长度的新字符串,并使用填充整个字符串的默认字符.
也就是说,如果你可以new String(10, '*')从那里创建一个新的字符串会很酷,长度为10个字符都有*.
因为这样的构造函数不存在,并且您无法从String扩展,所以您要么创建一个包装类,要么为您执行此方法.
此刻我正在使用这个:
protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
char[] array = new char[length];
int pos = 0;
while (pos < length) {
array[pos] = charToFill;
pos++;
}
return new String(array);
}
Run Code Online (Sandbox Code Playgroud)
它仍然没有任何检查(即,当长度为0时,它将不起作用).我首先构造数组,因为我相信它比使用字符串连接或使用StringBuffer更快.
其他人有更好的解决方案吗?
有没有更好的方法来为字符串添加x量的空白?
str = "blah";
x = 4;
for (var i = 0; i < x; i++){
str = ' ' + str;
}
return str;
Run Code Online (Sandbox Code Playgroud) 我需要增加一个字符串..假设aaa到zzz并在控制台中编写的每增量(增量是连一句话?).它会是这样的:
aaa
aab
aac
...
aaz
aba
abb
abc
...
abz
aca
acb
Run Code Online (Sandbox Code Playgroud)
等等.到目前为止,我通过这样做增加了一个字母:
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
string = "aaa";
string = string.replaceAt(2, String.fromCharCode(string.charCodeAt(2) + 1));
//string == "aab"
Run Code Online (Sandbox Code Playgroud)
但是,当涉及到最后一封信时,我迷失了,z然后它应该增加字母2(索引1)并重置最后一个字母a.
有没有人拥有或知道这个聪明的解决方案?谢谢!
我想使用相当新的beacon api.我在网上搜索但我找不到数据发送数据的大小限制.在参考文献中,它写的是用于少量数据,但我必须知道有多少......
我正在开发一个JavaScript函数,它接受两个值:十进制值的精度和十进制值的比例.
此函数应计算可以以该大小的十进制存储的最大值.
例如:精度为5且标度为3的小数最大值为99.999.
我有什么工作,但它不优雅.谁能想到更聪明的东西?
另外,请原谅使用这种古怪的匈牙利表示法.
function maxDecimalValue(pintPrecision, pintScale) {
/* the maximum integers for a decimal is equal to the precision - the scale.
The maximum number of decimal places is equal to the scale.
For example, a decimal(5,3) would have a max value of 99.999
*/
// There's got to be a more elegant way to do this...
var intMaxInts = (pintPrecision- pintScale);
var intMaxDecs = pintScale;
var intCount;
var strMaxValue = "";
// build the max number. Start …Run Code Online (Sandbox Code Playgroud) 如何用string一个char 创建一个JavaScript?
这是C#.
String text = new String('*',20);
Run Code Online (Sandbox Code Playgroud)
有一个简单的方法来做到这一点JavaScript?