Home > database >  simplify javascript array with loop syntax
simplify javascript array with loop syntax

Time:11-01

I have a javascript array defined as below:

var hexgon = ['M',r*Math.cos(0/180*Math.PI),r*Math.sin(0/180*Math.PI)                               
                                    ,r*Math.cos(30/180*Math.PI),r*Math.sin(30/180*Math.PI)
                                    ,r*Math.cos(90/180*Math.PI),r*Math.sin(90/180*Math.PI)
                                    ,r*Math.cos(150/180*Math.PI),r*Math.sin(150/180*Math.PI)
                                    ,r*Math.cos(210/180*Math.PI),r*Math.sin(210/180*Math.PI)
                                    ,r*Math.cos(270/180*Math.PI),r*Math.sin(270/180*Math.PI),
                                    ,r*Math.cos(330/180*Math.PI),r*Math.sin(330/180*Math.PI),'Z']

How to use a loop to simplify this logic?

CodePudding user response:

If you did not intend two commas in a row after the twelth element then this:

var hexgon = ['M', ...[0,30,90,150,210,270,330].flatMap(d => [r*Math.cos(d/180*Math.PI),r*Math.sin(d/180*Math.PI)]), 'Z']

CodePudding user response:

If you can have a constant value as a step that gets added to Math.cos() and Math.sin() statements we might be able to do something.

Let's say we want to add 30 each time to the each array's element, we can do something like this: (Also noticed there are M and Z characters at the beginning and end of your array)

const newHexgon = new Array(16);
newHexgon[0] = 'M';
newHexgon[newHexgon.length - 1] = 'Z';
let counter = 0;
let step = 30;
for (let i = 1; i < newHexgon.length - 1; i  = 2) {
  newHexgon[i] = Math.cos(((counter * step) / 180) * Math.PI);
  newHexgon[i   1] = Math.sin(((counter * step) / 180) * Math.PI);
  counter  ;
}

console.log(newHexgon);

I created an array with a length of 16 and set the first and last elements to "M" and "Z" as in your array. Then I will loop every two elements at a time i = 2 and set the Math calculations and after finished in each iteration the counter gets added by one.

  • Related