1

the following p5js code did not work , since the object in array are reference to the flower , how can i initialize the object with different values ?

var flowers;
var flower;

function setup()
{
    createCanvas(1000,500);
    base_x = width/2;
    base_y = height - 50;

    flowers = [];

    flower = {
        base_x: 0,
        base_y: height - 50,
        stem_h: 100,
        col: color(255,50,50)
    }

    for(var i = 0; i < 10; i++)
    {
        flower.base_x = i * 100;
        flower.stem_h = random(50,400);
        flower.col = color(
            random(0,255), 
            random(0,255),
            random(0,255)
            );
        flowers.push(flower);

    }
}
2

2 Answers 2

1

You can dereference the flower object before pushing into array by any of following three methods:

line flowers.push(flower); should be

flowers.push(Object.assign({}, flower));

OR

flowers.push({...flower});

OR

flowers.push(JSON.parse(JSON.stringify(flower)));
Sign up to request clarification or add additional context in comments.

Comments

0

How about pushing distinct objects into the array, instead of changing the same object over and over again.

var flowers = [];

function setup() {
  createCanvas(1000, 500);
  base_x = width/2;
  base_y = height - 50;

  for (var i = 0; i < 10; i++) {
    // Creates a new object in every iteration.
    // And there's no point in defining this variable globally.
    var flower = {
      base_x: i * 100,
      base_y: height - 50,
      stem_h: random(50, 400),
      col: color(
        random(0, 255),
        random(0, 255),
        random(0, 255)
      )
    };

    flowers.push(flower);
  }
}

or even

var flowers = Array.from({length: 10}, function(_, i){
  return {
    base_x: i * 100,
    base_y: height - 50,
    stem_h: random(50, 400),
    col: color(
      random(0, 255),
      random(0, 255),
      random(0, 255)
    )
  };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.