Wednesday, 21 January 2015

Arrays in Javascript

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script type="text/javascript">
//Variables are good to hold single values, but for cases where a variable should contain multiple values,
//we would have to rely on arrays. A JavaScript array is a collection of items arranged in an order,
//according to their index. Each item, in the array, is an element and has an index, which is used to access
//that element. Arrays are like a bookshelf that holds more than one book; each book having its unique location.
//Arrays are declared using the array literal notation []
var arrayOne = [1, 2, 3, 4];
alert(arrayOne[0]);
var arrayTwo = ["One", "Two", "Three", "Four"];
alert(arrayTwo[0]);
var multidimensionArray = [arrayOne, arrayTwo];
alert(multidimensionArray[1][2]);
//The second way of declaring an array is by using the Array class.
var bookshelf = new Array()
//Objects are another way of handling data. In arrays the indexes are commonly numerical;
//objects give us a robust way of assigning and retrieving data. Objects are derived from the object-oriented
//programming concept; a programming paradigm that is very popular. Objects are a virtual representation of real-time data;
//they allow us to organize our data into logical groups via properties and methods.
//Properties describe the state of the object, while methods describe the behavior of the object.
//Properties are a key-value pair that holds the information. Take a look at the following:
//Objects
var person = new Object();
person.firstname = "Nancy";
person.lastname = "G";
person.getFullName = function () {
alert(person.firstname + ' ' + person.lastname);
};
person.getFullName();
//In the previous example, we have instantiated a person object, and then added the firstname and lastname properties
//that described the object. We added behavior to the object by creating a method called getFullName ,
//the method accessed the object properties, retrieved the data, and alerted the output onto the screen.
//In this example the properties are accessed by the dot notation; we could also access a property by putting the
//property name in square brackets similar to an array, but it is not popular. This is shown as follows:
alert(person["firstname"]);
//The second way of creating an object is by using the curly braces. Here we are introduced to the this keyword,
//which provides a reference to the object's properties and methods, as shown in the following:
var personObj = {
"firstname": "Gale",
"lastname": "D",
"getFullName": function () { alert(this.firstname + ' ' + this.lastname); },
};
personObj.getFullName();
</script>
<title></title>
</head>
<body>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub