What is the syntax of literal objects in Javascript?

Asked

Viewed 120 times

4

Can anyone help me with this structure? I don’t know what it is or how it works.

var variavel = {
    teste1: '1',
    teste2: '2',
    teste3: '3'
};
  • What do you want to do? You need to give us some parameter to answer. Apparently everything is ok in such a short stretch.

  • I understand, thank you very much for your explanation.

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to proceed. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote on any question or answer you find useful on the entire site (if you have enough score).

3 answers

6

This is how to define an object. The members of the object are on the left side of the :, members' values are on the right side.

var variavel = {
    'teste1':'1',
    'teste2':'2',
    'teste3':'3'
};
console.log(variavel.teste1); //acessando o membro
console.log(variavel['teste2']); //sintaxes diferentes, mas mesmo resultado
var variavel2 = { //é mais comum fazer desta forma, ainda que funcione igual
    teste1:'1',
    teste2:'2',
    teste3:'3'
};
console.log(variavel2.teste1); //sintaxes diferentes, mas mesmo resultado
console.log(variavel2['teste2']);

Note that the keys serve to define objects, that is, pairs of keys (left side) and values (right side). If you use square brackets, you’re setting a data sequence.

var variavel3 = ['1', '2', '3'];
console.log(variavel3[0]);

I put in the Github for future reference.

Depending on the use can only do with double quotes, it is the case of JSON, although some interpreters accept with the simple.

  • I understand, thank you very much for your explanation.

5

That is the creation of an object with the properties teste1, teste2 and teste3. What you have on the left side is the property identifier, on the right side is the value.

It’s the same thing as doing the code below.

var variavel = {
    teste1: '1',
    teste2: '2',
    teste3: '3'
};

console.log(variavel.teste1);

1

This is an object. The structure follows the standard attribute and its value. This value can be a String, boolean, int, function(), other object. Follow an example:

var objeto = {
    atributoUm: 'String',
    atributoDois: 10, // inteiro
    atributoTrês: true, //boolean,
    atributoQuatro: [], //array
    atributoCinco: {}, // outro objeto
    atributoSeis: function () {} //function,
    atributoSete: funcao.metodo() //método
}

to access any attribute, just call your object attribute point. Example:

objeto.atributoUm // acessa esse específico atributo deste objeto

Browser other questions tagged

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