Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extend a list of object array using for loop

// First i=0
let posi_val=[{top: '3px', left: '2px'}];
// Second i=1
let posi_val=[{top: '3px', left: '2px'},{top: '6px', left: '4px'}];
// Third i=2
let posi_val=[{top: '3px', left: '2px'},{top: '6px', left: '4px'},{top: '12px', left: '8px'}];

Dear all, the above code is part of code to create css class (multiple red dots) on different postion, may I ask how to extend the list of object arrays as shown in the example above such that it is using for loop and the top and left numbers are extended by 2 times the previous value so its 3,6,12 and 2,4,8 px and so on?

I have tried using JSON.parse to rewrite the entire string again but its quite confusing, so are there any simpler method to construct this array? A demo can be found at codepen here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

someting like that ?

console.log(  creatList( 5 )  )

function creatList( counter )
  {
  let t = 3; l=2; res=[];
  for(let i=0;i<counter;i++)
    {
    res.push( {top:`${t}px`,left:`${l}px`} )
    t *= 2
    l *= 2
    }
  return res
  }
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading