This is the 13th day of my participation in Gwen Challenge

Object definition

In JavaScript, objects are defined by “{}”. This approach is called literal syntax for objects. A literal is a quantity that represents data and types written directly in source code. (e.g. numeric, character, array, etc.)

The members of the object are stored as key-value pairs, separated by commas.

// Create an empty object var o1 = {}; Var o2 = {name:'Tom'}; Var O3 = {name:'Jane',age:22,gender:'Girl'}; </script>Copy the code

We often indent and wrap code when objects have many attributes.

var o3 = {
        name:'Jane',
        age:22,
        gender:'Girl'
    };
Copy the code

The JSON data format is mentioned here:

var o4 = {"name":"Jane","age":22,"gender":"Girl"}; JSON can be used to store not only objects but also numbers, strings, arrays, and other types of data.Copy the code

Accessing object members

After creating an object, click. Members of objects that can be accessed. Objects in JavaScript are dynamic and you can manually assign properties or methods to them.

<script>
    var o1 = {};
    o1.name = "Jane";
    o1.age = 22;
    o1.print = function(){
        console.log(this.name);
    }
    o1.print();
    </script>
Copy the code

If the member name of an object is uncertain, the variable member name can be implemented using the “[]” syntax, as shown in the following example:

<script> var o1 = {}; var key = 'id'; o1[key] = 123; // o1['id'] = 123, o1.id = 123; console.log(o1.id); </script>Copy the code

Object member traversal

For in iterates through the members of the object

<script>
    var o3 = {
        name:'Jane',
        age:22,
        gender:'Girl'
    };
    for(var i in o3){
        console.log(o3[i]);
    }
    </script>
Copy the code

You can also go through O3iTo call a method in an object.

The IN operator is used to determine whether a member of an object exists.

<script>
    var o3 = {
        name:'Jane',
        age:22,
        gender:'Girl'
    };
    console.log('name' in o3);
    </script>
Copy the code

So that’s a little bit of a primer on objects, and next time we’ll look at another way to create objects.