views:

99

answers:

6

Is there a way to assign a default values to arrays in javascript?

ex: an array with 24 slots that defaults to 0

+1  A: 

No.

You have to use a loop.

var a = new Array(24);
for (var i = a.length-1; i >= 0; -- i) a[i] = 0;
KennyTM
Not true, see above.
sleske
Technically it's still a loop, moved into a function.
KennyTM
A: 

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);
CrazyJugglerDrummer
I think you're missing `return array;`
Roman Stolper
yeah that would help...Thanks :D
CrazyJugglerDrummer
A: 

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 ];
tvanfosson
+4  A: 
Array.prototype.repeat= function(what, L){
 while(L) this[--L]= what;
 return this;
}

var A= [].repeat(0, 24);

alert(A)

kennebec
What's with the weird (Javascript-wise) naming conventions? (@ the use of capital letters.)
trinithis
quite clever! thanks
Derek Adair
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");
trinithis
+1  A: 
(new Array(5).toString().replace(/,/g, "0,") + "0").split(",")

// ["0", "0", "0", "0", "0"]
serious