To generate a sequence of numbers or characters in JavaScript, we can create our own function. We create the makeArray function that takes the count and content parameters. count has the number of entries in the array. content has the content we want to add, which can be generated from a function or any value.
The syntax to create a sequence in Oracle is: CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value; sequence_name. The name of the sequence that you wish to create.
Without a for loop, here is a solution:
Array.apply(0, Array(8)).map(function() { return 1; })
The explanation follows.
Array(8)
produces a sparse array with 8 elements, all undefined
. The apply
trick will turn it into a dense array. Finally, with map
, we replace that undefined
the (same) value of 1
.
The original question was edited. So the updated example answers:
To fill the same content:
Array(8).fill(1)
//=> [1, 1, 1, 1, 1, 1, 1, 1]
To fill sequential numbers, starting from 5:
Array(8).fill().map((element, index) => index + 5)
//=> [5, 6, 7, 8, 9, 10, 11, 12]
To fill sequencial characters, starting from 'G':
Array(8).fill().map((element, index) => String.fromCharCode('G'.charCodeAt(0) + index))
//=> ["G", "H", "I", "J", "K", "L", "M", "N"]
You can make your own re-usable function I suppose, for your example:
function makeArray(count, content) {
var result = [];
if(typeof content == "function") {
for(var i = 0; i < count; i++) {
result.push(content(i));
}
} else {
for(var i = 0; i < count; i++) {
result.push(content);
}
}
return result;
}
Then you could do either of these:
var myArray = makeArray(8, 1);
//or something more complex, for example:
var myArray = makeArray(8, function(i) { return i * 3; });
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 :)
for (var i=8, a=[]; i--;) a.push(1);
One liner:
new Array(10).fill(1).map( (_, i) => i+1 )
Yields:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Using Jquery:
$.map($(Array(8)),function(val, i) { return i; })
This returns:
[0, 1, 2, 3, 4, 5, 6, 7]
$.map($(Array(8)),function() { return 1; })
This returns:
[1, 1, 1, 1, 1, 1, 1, 1]
2016 - Modern Browser functionality has arrived. No need for jquery all the time.
Array.from({length: 8}, (el, index) => 1 /* or index */);
You can substitute the arrow function with a simple callback function to reach a slightly wider range of supported browsers. It's, for me at least, the easiest way to iterate over an initialized array in one step.
Note: IE is not supported in this solution, but there is a polyfill for that at developer.mozilla.org/...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With