Thursday 30 August 2018

JavaScript: . Vs []: accessing properties

As I said, there are two ways to access properties associated with an object.

Syntax
var a = object.property; // Access the value associated with given property using '.' notation.

var a = object["property"]; // Access the value associated with given property using [].

If a property has space (or) start with a number, you can only access using [] notation.

Ex:
person1["first name"] = "Hari Krishna";
person1["last name"] = "Gurram";

objIndex.html
<!DOCTYPE html>

<html>

<head>
    <title>Index Notation</title>
</head>

<body>
    <script type="text/javascript">
        var person1 = new Object();

        person1["first name"] = "Hari Krishna";
        person1["last name"] = "Gurram";

        document.write("person1['first name'] : " + person1["first name"] + "<br />");
        document.write("person1['last name'] : " + person1["last name"] + "<br />");
    </script>
</body>

</html>

Suppose your application reads a property name and gives you the value associated with that property, you need to use [] notation.

properties.html
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        var capitals = {
            india: "New Delhi",
            sweden: "Stockholm",
            japan: "tokyo"
        }

        var str = prompt("Enter country name")
        alert("Capital of " + str + " is " + capitals[str]);
    </script>
</body>

</html>

Load above page in browser, it prompts for country name and return the capital of the country.

One more thing is you can iterate through all the properties and values associated with the property only by using [] notation.


Object.html
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        function Employee(firstName, lastName, id) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = id;
        }

        function printEmployee(employee) {
            for (property in employee) {
                document.write(property + " : " + employee[property] + "<br />");
            }
            document.write("<br />");
        }

        /* Create an object of type Employee */
        var emp1 = new Employee("Hari Krishna", "Gurram", 123);
        var emp2 = new Employee("Sankalp", "Dubey", 987);

        printEmployee(emp1);
        printEmployee(emp2);
    </script>
</body>

</html>




Previous                                                 Next                                                 Home

No comments:

Post a Comment