I have an array that’s already been instantiated in the objects class (a.k.a. prototype) with new Array(), but has no data. After creating an object, I usually define its initial data all at once. Is there a way to assign all this data without doing 100 individual lines of push? Is there a way to assign a large amount of data to an existing array at once? Perhaps something like:
myArray.push([1,2,3]);
I could use:
myArray = myArray.concat([1,2,3]);
but that creates an entirely new array, which seems more expensive and messy when all I’m really doing is assigning an existing array its initial data.
Is there a better way to do this?
If we’re talking about an existing array, you don’t need several calls to
.push(). You can pass several arguments in one call.If the items to be added are in a different Array, you can use
.applyto add them individually.But for a new Array, use either the literal syntax to create and initialize at the same time, or you can pass multiple items to the Array constructor.
In your question you state that the Array is on the constructor’s
.prototype. As I noted in the comment above, that’s usually not what you want. But if it is intended to be shared in this case, then the first two solutions above will work.