Home > other >  How to extend a list of object array using for loop
How to extend a list of object array using for loop

Time:01-20

// 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.

CodePudding user response:

something 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<<=1, l<<=1;
    }
  return res
  }
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

CodePudding user response:

Does this do what you want?

const cssPositions = (initialTop, initialLeft, count) => {
    let posi_val = [];
    for(i=0; i<count; i  ){
        cssString = `{ top: '${initialTop}px', left: '${initialLeft}px' }`;

        initialTop  = initialTop;
        initialLeft  = initialLeft;

        posi_val.push(cssString);
    }
  
  return posi_val;
}

// Calling the function 
console.log(cssPositions(3,2,3));

  • Related