Is there a way to assign a default values to arrays in javascript?
ex: an array with 24 slots that defaults to 0
Is there a way to assign a default values to arrays in javascript?
ex: an array with 24 slots that defaults to 0
No.
You have to use a loop.
var a = new Array(24);
for (var i = a.length-1; i >= 0; -- i) a[i] = 0;
You can't specialize an initial value, so use the old fashioned way of looping through the contents and assigning the values. Here's a nice library function for the job:
Array.prototype.withDefaultValue = function(length, default) {
var array = new Array(length);
for (var x=0; x<array.length; x++)
array[x]=default;
return array;
}
//usage:
var my_array = Array.withDefaultValue(24,0);
A little wordy, but it works.
var aray = [ 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0 ];
Array.prototype.repeat= function(what, L){
while(L) this[--L]= what;
return this;
}
var A= [].repeat(0, 24);
alert(A)
I personally use:
function replicate (n, x) {
var xs = [];
for (var i = 0; i < n; ++i) {
xs.push (x);
}
return xs;
}
Example:
var hellos = replicate (100, "hello");
(new Array(5).toString().replace(/,/g, "0,") + "0").split(",")
// ["0", "0", "0", "0", "0"]