Updating the property of an object originally set to an undefined array element

var A = [];

var obj = {
    x: A[1],
    y: 'hello'
};

A[1] = 1;

console.log(JSON.stringify(obj)); // {"y":"hello"}

By the time I use objin console.log(), it is A[1]already defined.

How can I get the "last" objwith all its properties updated? So {"x":1,"y":"hello"}, when will we get it done console.log()?

+4
source share
4 answers

. , x , , , , , . , A x.

var A = [];

var obj = {
    x: A,
    y: 'hello'
};

A[1] = 1;

alert(JSON.stringify(obj));

:

var A = [];
var B = {};
A[1] = B;

var obj = {
    x: A[1],
    y: 'hello'
};

B.z = 1;

alert(JSON.stringify(obj));
+3

A[1] = 1; , obj . , obj.x undefined.

var A = [];
A[1] = 1;
var obj = {
  x: A[1],
  y: 'hello'
};
document.body.textContent = JSON.stringify(obj);
Hide result
+3

, obj.x :

var obj.x. obj.x ,

 var variable= 2
 var obj = {
     x: function() {
         return variable;
     },
     y: 'hello'
  };

  variable = 5;

  console.log(obj.x()); //prints 5
+3

Javascript . obj.x = 1 .

0
source

Source: https://habr.com/ru/post/1624146/


All Articles