Alvaro
Alvaro

Reputation: 21

Objects with arrays

I'm a bit new with Javascript and I'm trying to create objects with arrays inside. In C I have sort it out easily using structs, but in Javascript I'm a little bit lost. Here's my code:

function Switch() {
  var title;
  var toggleModeEnable;
};

function Layer () {
  sw = [8];
  for (j = 0; j < 8; j++) {
      sw[j] = new Switch();
  };
};

var lr = [10];
for (i = 0; i < 10; i++) {
    lr[i] = new Layer();
};

Obviously, this doesn't work. What I'm trying to achieve is having an array (lr) of 10 elements. Each of them should be an ayyay of 8 elements (sw), and each one with two properties (title and toggleModeEnable), and access them with something like this:

lr[1].sw[3].title

But something like this throws an error like:

"Uncaught TypeError: Cannot read property '3' of undefined at :1:9"

What I'm missing here?

Upvotes: 1

Views: 87

Answers (3)

ATD
ATD

Reputation: 1364

There are a couple of things you should take into account.

  • Firstly, variables should be defined using let or const, not var. Using var to define variables can cause problems in "use strict" mode, as stated in the docs

  • Secondly, functions should return something.

  • Thirdly, neither the Switch nor the Layer functions take arguments, so they'll return the same values.

  • Fourthly, as they are functions, you shouldn't use new unless they have been defined as objects – you just call the function.

  • Finally, as the objects stored on the arrays have no key names, you only need to use lr[0][0] to get the first value from the first object in the array.

So, taking all that into account, try this:

function Layer (i) {

  function Switch(j) {
    let title = "aaa." + i + "." + j;
    let toggleModeEnable = false;
    return {title, toggleModeEnable};
  };

  let sw = [8];
  for (j = 0; j < 8; j++) {
    sw[j] = Switch(j);
   };
   
   return sw;
};

let lr = [10];
for (i = 0; i < 10; i++) {
    lr[i] = Layer(i);
};

console.log(lr[1][3]);
console.log(lr[1][6]);

Upvotes: 1

altruios
altruios

Reputation: 1073

you can add parameters to make the structure more flexible.

const test = LR(10);
console.log(test);
function LR(length){
    const lr=[];
    for (let i = 0; i < length; i++){
      lr.push(LAYER(8));
      return lr;
   }
}

function SWITCH(title){
  return {
    title:title,
    toggleModeEnable:false
  }
}
function LAYER(size){
  const sw=[];
   for (let j = 0; j < size; j++) {
    sw.push(SWITCH(""));
  }
  return sw;
}

Upvotes: 0

user14311453
user14311453

Reputation:

I believe you're looking for:

function Switch() {
  this.title = '';
  this.toggleModeEnable = false;
}

function Layer () {
  this.sw = [];
  for (let j = 0; j < 8; j++) {
    this.sw.push(new Switch());
  }
}

const lr = [];
for (let i = 0; i < 10; i++) {
  lr.push(new Layer());
}

Upvotes: 3

Related Questions