I\'m trying to set default values on an uninitialized array using the map function but it doesn\'t seem to work, any ideas on how to set default values?
Consider thi
Building on a previous answer there is new shorter syntax. The OP wanted to create an array of N items initialized with 0.
var N = 10;
var x = new Array(N).fill(0);
// x is now: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
You also don't need the new
- it's optional in this context.
Check the compatibility of your target platform and/or use a pollyfill if not available.
You can populate an array with zeros using this function:
function fillArrayWithNumber(n) {
var arr = Array.apply(null, Array(n));
return arr.map(function (x, i) { return 0; });
}
fillArrayWithNumber(5); // [0,0,0,0,0]
Or with a small change you can use indexes instead:
function fillArrayWithIndex(n) {
var arr = Array.apply(null, Array(n));
return arr.map(function (x, i) { return i; });
}
fillArrayWithIndex(5); // [0,1,2,3,4]
Fiddle