jonan
jonan

Reputation: 217

Simple Javascript: Running a function over an array

I am trying to create an array of vertices, and then run the 'rect' function over this array to display an arbitrary amount of rectangles. Right now, I have:

var vertices = new Array();

function setup() {
    createCanvas(600, 600);
    ...
    iter(width/2 - c/2, height/2 - c/2, c);
    var i;
    for (i = 0; i < vertices.length; i++) {
        fill(200);
        rect(vertices[i]);
    }
}

And then:

function iter(x, y, len) {
    r_1 = random(0, 1);

    if (r_1 < 0.5){
        vertices.push(x, y - len*0.5, len*0.5, len*0.5);
    }
}

I have seen lots about using map or foreach to run functions over arrays but I don't know why this doesn't work (specifically, using a for loop to run a function over an array). I am obviously very new to all this stuff! An explanation of what I seem to misunderstand would be very much appreciated.

Thanks

Upvotes: 3

Views: 59

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370999

When you do

vertices.push(x,y-len*0.5,len*0.5,len*0.5)

you're calling push with four arguments, so four items get pushed to the array. Because you're calling rect with verticies[i] later, it sounds like each item of verticies should be a data container of some sort - an array or an object, otherwise the points of each vertex will be separated out over multiple indicies. For example, if you were to use an array:

function iter(x, y, len) {
  r_1 = random(0, 1);
  if (r_1 < 0.5){
    vertices.push([x, y - len*0.5, len*0.5, len*0.5]);
  }
}

And then spread each array in the vertex array into the rect argument list:

function setup() {
  createCanvas(600, 600);
  // ...
  iter(width/2 - c/2, height/2 - c/2, c);
  var i;
  for (i = 0; i < vertices.length; i++) {
    fill(200);
    rect(...vertices[i]);
  }
}

This assumes that rect is a function that accepts 4 arguments. (you could also change rect so that it accepts a single array as an argument instead, and avoid the spread syntax, if you wanted)

You also might consider using an array literal rather than new Array - calling the Array constructor is rarely a good idea:

var vertices = [];

Upvotes: 1

Related Questions