0

I have this piece of code but I am want to know if there is a simpler way of doing it?

cols = new Array("white","blue","green","pink");

pg = new Array();
pg[0] = new Object();
pg[0].opt = new Array();
pg[0].opt[0] = new Object();

// Instead of doing individually
/* 
pg[0].opt[0].white = new Array();
pg[0].opt[0].blue  = new Array();
pg[0].opt[0].green = new Array();
pg[0].opt[0].pink  = new Array();
*/
// Can I write a for loop through the colours;
/* 
for(n=0; n<=3; n++){
   pg[0].opt[0].cols[n] = new Array();
};
mplungjan
  • 169,008
  • 28
  • 173
  • 236
S.S
  • 5
  • 4
  • 1
    There's no such thing as a `for...next` loop – Andreas Sep 28 '21 at 13:07
  • 4
    Why is this tagged with `jquery`? jQuery is not related with the problem/question. – Andreas Sep 28 '21 at 13:08
  • 2
    Is there a specific reason why you use the constructors of `Array` and `Object`? Why not simply `[ ]` and `{ }`? `pg = [ { opt: [ { } ] } ]` – Andreas Sep 28 '21 at 13:10
  • PLEASE: `for(let i=0; i – mplungjan Sep 28 '21 at 13:10
  • 1
    Other than the fact all of the code above relies on [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) -- declare your variables! :-) -- your version at the end is very close, you've just used `cols` slightly incorrectly. It would be just `pg[[0].opt[0][cols[n]] = new Array();` (but don't use `new Array()` or `new Object()`, use `[]` and `{}`). Also note that you can start with `pg = [{opt: [{}]}]` rather than those four initial assignments. – T.J. Crowder Sep 28 '21 at 13:11
  • Thanks but I have read the comments and still don't really get it. – S.S Sep 28 '21 at 13:57

0 Answers0