1

I created a racing html 5 canvas and JS project that makes use of a colour API. I'm looking to clean up my code. Is there a way I can change the code below into a for loop to save on the amount of code that has to be re-typed? I was thinking of a for loop but can't get my head around the idea of how I would chnage the values for the attributes on each iteration?

            c1 = new Car({ x: 0, y: 100, colour: "#" + json.colors[0].hex, windowsColour: "#" + json.colors[1].hex, number: 1 });
        c2 = new Car({ x: 0, y: 250, colour: "#" + json.colors[3].hex, windowsColour: "#" + json.colors[2].hex, number: 2, });
        c3 = new Car({ x: 0, y: 400, windowsColour: "#" + json.colors[4].hex, colour: "#" + json.colors[5].hex, number: 3, });
        c4 = new Car({ x: 0, y: 550, windowsColour: "#" + json.colors[6].hex, color: "#" + json.colors[7].hex, number: 4 });
1
  • @jaquarh hello there Commented Jul 24, 2022 at 14:10

1 Answer 1

1

you can use array c[...] and use a code like this

for (i=1; i<=4; i++) {
  c[i] = new Car({ x: 0, y: (i+1)*100, colour: "#" + json.colors[i].hex, windowsColour: "#" + json.colors[i+1].hex, number: (i+1) });
}

this will create c[1]...c[4]

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you:) Had to make a few tweaks to it with the y position but other than that worked great.. Also implemented it in other parts of my code :-)

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.