How do I get a field in an object in javascript?
var test = {}
undefined
test = 1
1
test.example = 10
10
test.example
undefined
console.log(test.example)
undefined
How do I get a field in an object in javascript?
var test = {}
undefined
test = 1
1
test.example = 10
10
test.example
undefined
console.log(test.example)
undefined
JavaScript is a dynamic, weak typing language. One of its characteristics is that variables can store any type of value, and can change type without this generating any error or warning.
With that in mind, see 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"
Since test
contains a number, there is no point in trying to assign properties anymore, since numbers are primitive types, not objects (there are even wrappers objects for numbers, but I will not go into details since you do not use them in the question code).
Responding to the title question: once having an object, just assign a new property:
var test = {};
test.example = 10;
console.log( test.example ); // 10