Lau Lau - 1 year ago 78
Javascript Question

Execute function inside object

I'm using an array of objects to randomly print items in a canvas. Each object should have a different random color, but the way I wrote the code every object gets the same one.

var arrayOfObjects = [
{x: 1, y: 5, r: 10, color: pickColor}, //gets random color
{x: 2, y: 6, r: 10, color: pickColor} // should get a different color
//and so on...

I tried to replace the
variable with a function to be executed inside each object so that they all get a different color, but I can't seem to use this value to pick a color inside my color's array.

This obviously doesn't work :

{x: 1, y: 5, r: 10, color: colorList[parseInt(Math.random() * colorList.length)]},

EDIT : this code works, the problem came from an apparently unrelated line with no hints in debugging tool.
Thanks for your answers

Answer Source

Make pickColor a function and call it multiple times:

var colorList = ["#E57373", "#F06292", "#BA68C8", "#9575CD", "#7986CB", "#64B5F6", "#DCE775", "#AED581", "#81C784", "#FFD54F"];

function pickColor() {
    var randIndex = parseInt(Math.random() * colorList.length);
    return colorList[randIndex];

var arrayOfObjects = [
    {x: 1, y: 5, r: 10, color: pickColor()},
    {x: 2, y: 6, r: 10, color: pickColor()},
    //and so on...

The effect is just the same as in your second snippet, except you don't have to repeat yourself for every object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download