0

I'm having trouble accessing a property of an object I store in an array.

I store the properties like so:

let lights = [];

let newlightinfo = {
  active: true, // default value
  directional: false, // default value
  x: 0, // default value
  y: 1, // default value
  z: 0, // default value
  ia: vec3(75, 75, 75), // default value
  id: vec3(175, 175, 175), // default value
  is: vec3(RGB, RGB, RGB) // default value
}

let addlightbutton = {
    add: function() {
      if (lights.length <= MAX_LIGHTS) {
        let lightinfo = {
          active: newlightinfo.active,
          directional: newlightinfo.directional,
          x: newlightinfo.x,
          y: newlightinfo.y,
          z: newlightinfo.z,
          ia: newlightinfo.ia,
          id: newlightinfo.id,
          is: newlightinfo.is
        }
        lights.push(lightinfo);
      }
    }

I also tried to simply do let lightinfo = newlightinfo, but it also didn't work, which makes sense.

I'm trying to do:

function lightInfo()
    { 
        if(lights.length > 0) {
            console.log(JSON.stringify(lights[0]));
            console.log(JSON.stringify(lights[0].x));
            // Light information
            for(let i = 0; i < MAX_LIGHTS; i++) {
                let x = lights[i].x; // error line
...

But I'm getting an error - Uncaught TypeError: Cannot read properties of undefined (reading 'x').

I can't understand why since when printing out lights[0] and lights[0].x right before accessing my array everything seems right.

Any ideas on why this is happening?

Kob
  • 77
  • 6
  • 1
    Please post a [mcve]. You can use a [Stack Snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) to make it executable. – Barmar Dec 21 '21 at 20:06
  • I'm using dat.gui to make the button functional in a browser interface, I don't think I can use that in a snippet too. – Kob Dec 21 '21 at 20:11
  • 1
    We don't need that, we just need you to post enough so we can see how you're calling the `add()` function and where you're trying to read the property after doing that. – Barmar Dec 21 '21 at 20:12
  • If you call `add()` asynchronously, make sure you don't try to read the array before that completes. – Barmar Dec 21 '21 at 20:12
  • I can't seem to be able to make my snippet work, sorry. – Kob Dec 21 '21 at 20:25
  • Then we can't tell what you're doing wrong. – Barmar Dec 21 '21 at 20:28
  • 1
    BTW, you can simplify that to `let lightinfo = {...newlightinfo};` – Barmar Dec 21 '21 at 20:30

1 Answers1

0

this error only happens if array at 0 index is null, so if you add it in some way then use it, I guess maybe adding happens after accessing lights[0] so it's better to check if adding some how take longer than you think because of javascript nature