Is it possible to create an array by defining the length and value for the array element?
If you mean, some kind of pre-initializing constructor or fill operation, no, JavaScript doesn't have that.
If you know you want three elements as of when you're writing the code, you can do this:
a = [0, 0, 0];
It's called an array initializer.
If you don't know in advance (e.g., when writing the code) how big the array should be, you can just fill it as necessary:
a = [];
var index;
for (index = 0; index < initialSize; ++index) {
a[index] = 0;
}
Note that you don't have to pre-allocate room in the array; the array can "grow" as required. (This may seem strange, but standard JavaScript arrays aren't really arrays at all, although JavaScript engines will frequently try to use true arrays as an optimization if they think they can.)
But if you want to, you can tell the engine engine in advance what length you want, by using:
a = new Array(initialSize);
...rather than a = [];
above. (More on this near the end.)
If you wanted to, you could add a function to the Array
function object to do that:
Array.createFilled(length, value) {
var a = new Array(length); // Or of course, `var a = [];`
var i;
for (i = 0; i < length; ++i) {
a[i] = value;
}
return a;
}
Then using it in the various places you want a pre-filled array:
var a = Array.createFilled(3, 0); // 0,0,0
Side note: Always be sure to declare your variables, e.g., have a var a;
somewhere prior to the line above.
Obviously, telling the engine in advance how big the array should be would let it do better optimization, right? Not necessarily! It may help some engines (a small bit), hinder others (a small bit), and/or make no difference:
