crash2020
crash2020

Reputation: 23

Is there a way to determine the number of values you want to push in a javascript array?

I've been trying to add the same vec4 colors into an already existing array but I want to add n number of instances of the same color. For example, I created an array that holds 36 values of the same color:

var colours = new Array(36).fill(vec4( 0.01,0.43,0.79,1.0 ));

Now,I want to add another color value 36 times into the same existing array.

colours.push(vec4( 0.01,0.43,0.79,1.0 ));

This just inserts one instance of the value I want, but I want to add 36 of them. Instead of writing multiple push lines, is there a way to push 36 values all together?

Upvotes: 2

Views: 114

Answers (2)

Codebreaker007
Codebreaker007

Reputation: 2989

You could do it in a for loop

for (var i=0; i<36;i++){
   colours.push(vec4( 0.01,0.43,0.79,1.0 ));
}

Upvotes: 1

Barmar
Barmar

Reputation: 781068

Use the ... syntax to spread the new array into multiple arguments.

colours.push(...new Array(36).fill(vec4( 0.01,0.43,0.79,1.0 )))

Or use the concat() method:

colours = colours.concat(new Array(36).fill(vec4( 0.01,0.43,0.79,1.0 )));

The second method creates a new array rather than pushing into the existing array.

Upvotes: 3

Related Questions