Is there way of generating a string made up of 250 underscores, without using a loop? I want to avoid writing code like this:
var myString= '';
for (var i=0; i < 250; i++) {
myString += '_';
}
Is there way of generating a string made up of 250 underscores, without using a loop? I want to avoid writing code like this:
var myString= '';
for (var i=0; i < 250; i++) {
myString += '_';
}
var myString = "__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________";
Why do you want to generate it? And why do you want to avoid a for
loop?
There's no built-in solution but the question Repeat String - Javascript has a nice solution:
If you don't want to alter the String prototype you can just do:
var num = 250;
var myChar = '_';
var myString = new Array(num + 1).join(myChar);
This is creating an array of 251 undefineds an then joining them by your character.
Since undefined is '' (empty string) when converted to a string in .join()
, this gives you the string you're after.
Use a constant that is longer that the longest number of underscores and use substring()
to get as many as you need.
Its a bit of a hack, but you could do something like:
var arr = new Array(251);
var lineStr = arr.toString().replace(/,/g, "_");
Here's a function which creates the string in (more or less) logarithmic runtime:
function repeat(string, times) {
if(!(times = +times)) return ''; // convert to number; check for NaN, 0
var result = '' + string, i = 1;
for(; i * 2 <= times; i *= 2) result += result;
for(; i < times; ++i) result += string;
return result;
}
var u250 = repeat('_', 250);
Hopefully, I didn't mess up the loop conditions ;)
Also, Aaron's suggestion can be automated:
function underscores(count) {
while(count > underscores.buffer.length)
underscores.buffer += underscores.buffer;
return underscores.buffer.substring(0, count);
}
underscores.buffer = '_';
var u250 = underscores(250);