How to refer to the attribute itself of a Javascript object?

Asked

Viewed 66 times

0

I have an array of objects:

    window.matObj = [
    
    	{
    		id: 11,
    		x: aleatorio(3,9),
    		y: aleatorio(3,9),
    		resposta: (window.matObj[0].x + window.matObj[0].y),
    		enunciado: window.matObj[0].x + " + " + window.matObj[0].y
    	},
    
    	{
    		id:12,
    		x: aleatorio(3,9),
    		y: aleatorio(3,9),
    		resposta: (window.matObj[1].x + window.matObj[1].y)
    	},
    
    ];

However, when executing the application, it gives the following error:

Error in Undefined: Typeerror: Undefined is not an Object (evaluating 'window.matObj[0]')

I believe I’m referencing the attributes of each object (x and y) in the wrong way.

How the right way would be?

  • I wish I could do that too, make the code more readable

1 answer

4


This is because you’re trying to access data from an object that hasn’t even been created yet, and so it can’t be referenced by itself. You must create it first to then get values.


window.matObj = [

    {
        id: 11,
        x: aleatorio(3,9),
        y: aleatorio(3,9)
    },

    {
        id:12,
        x: aleatorio(3,9),
        y: aleatorio(3,9)
    },
];

window.matObj[0].resposta = (window.matObj[0].x + window.matObj[0].y);

window.matObj[0].enunciado = window.matObj[0].x + " + " + window.matObj[0].y;


window.matObj[1].resposta = (window.matObj[1].x + window.matObj[1].y);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.