If the property to be calculated only requires one statement, it is pretty simple
let object = {
array: new Array(10)
};
Alternatively I can also do the following (though I don’t like it as much)
let object = {};
object.array = new Array(10);
But what if I want to (e.g.) initialize the array with values of 0 (by deafult the values are "undefined")? I can only do it the second way
let object = {};
object.array = new Array(10);
for(let element of array){
element = 0;
}
The closest thing to the first method that comes to mind might be doing something like this
let object = {
array: (function(){
let array = new Array(10);
for(let element of array){
element = 0;
}
return array;
})()
}
Maybe there is a simpler way to do this that I do not know of?
Edit: The array was just the first thing that came to mind when thinking of an example. My problem does not lie exclusively on initializing an array, I am looking for a more general solution than using Array.fill().
4
Answers
Just use Array.fill:
Or, to do a slightly more complex array initialization:
To initialize an array of length 10, with the number 1, except in indices 4 and 7:
You can also use arrow functions and comma expressions (but it can easily start to become unreadable). Note that the arrow function declares parameters that it can use as variables, instead of having to do
let x =
, which would require braces.I recommend that instead of doing complex one-liners, you create your own separate helper functions. This will maximise code readability. For example, you could create a helper function called
function createArrayWithRandomValues(length, upperBound)
.You can use
fill
to fill array with0
as:Also, you can use
Array.from
as:There are lots of ways to initialize an array. Here are some examples based on your requirements:
Array.fill
This is useful if your array consists a single value
Array.from
This is useful if want your array elements based on their original value or indices.
This is useful if you want to dynamically control how your array is formed.
Array.with
This is useful for "I don’t want to change the entire array to 0, but only the value of the 4th and 7th element"
You can use an IIFE to perform more complex inline calculation of property values from within an object initializer. As an example based on the posted code: