How to put a field in a javascript object?

Asked

Viewed 36 times

2

Like putting a field in a javascript object?

var test = {}
undefined
test = 1
1
test.example = 10
10
test.example
undefined
console.log(test.example)
undefined
  • Could you explain better what you intend to do? On which page you want to create a field?

1 answer

4


Javascript is a dynamic, weak typing language. One of its characteristics is that variables can store any type of value, and can change types without generating any error or warning.

With that in mind, look what you’ve done:

// Declara uma variável e guarda um objeto nela
var test = {};
console.log( typeof test ); // "object"
// Troca o valor da variável por um número
test = 1;
console.log( typeof test ); // "number"

From the moment when test contains a number, it is no longer useful to try to assign properties, since numbers are primitive types, not objects (until there are objects Wrappers for numbers, but I won’t go into details since you don’t use them in the question code).

Answering the title question: once you have an object, simply assign a new property:

var test = {};
test.example = 10;
console.log( test.example ); // 10

  • Thank you! I imagined something similar, but it took me a while to accept this behavior, I believed that the primitive would not accept the proposal and would raise an exception.

  • In fact, when you try to assign a property to a primitive, it cradles that primitive into an object, but discards that object at the end of the statement. That mechanism is what makes things like (10).toString(); // "10".

Browser other questions tagged

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