Is there a way to generate sequence of characters or numbers in javascript?
For example, I want to create array that contains eight 1s. I can do it with for loop, but wondering whether there is a jQuery library or javascript function that can do it for me?
Advertisement
Answer
You can make your own re-usable function I suppose, for your example:
JavaScript
x
14
14
1
function makeArray(count, content) {
2
var result = [];
3
if(typeof content == "function") {
4
for(var i = 0; i < count; i++) {
5
result.push(content(i));
6
}
7
} else {
8
for(var i = 0; i < count; i++) {
9
result.push(content);
10
}
11
}
12
return result;
13
}
14
Then you could do either of these:
JavaScript
1
4
1
var myArray = makeArray(8, 1);
2
//or something more complex, for example:
3
var myArray = makeArray(8, function(i) { return i * 3; });
4
You can give it a try here, note the above example doesn’t rely on jQuery at all so you can use it without. You just don’t gain anything from the library for something like this 🙂