But Array is little different..
We call Arrays using Index. The first index is 0 (Zero-based Index).
To Create an Array :---
var array_name = [item1, item2, ...];
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
Output: Saab,Volvo,BMW
Another way of creating Array is
var Array_name = new Array( );
E.g:
<p id="demo"></p>
<script>
var cars = new Array("Maruthi", "Fiat", "Nissan");
document.getElementById("demo").innerHTML = cars;
</script>
Output: Maruthi, Fiat, Nissan
Accessing Array
1. Using indexing Method
<p id="car_info"></p>
<script>
var cars = ["Maruthi", "Fiat", "Lamborgini"];
document.getElementById("car_info").innerHTML = cars[0];
</script>
Output: Maruthi
<script>
var cars = ["Maruthi", "Fiat", "Lamborgini"];
document.getElementById("car_info").innerHTML = cars[0];
</script>
Output: Maruthi
2. Calling the Name inside curly braces
<p id="first"></p>
<script>
var person = {firstName:"Parathan", lastName:"Thiyaa", age:19};
document.getElementById("first").innerHTML = person["firstName"];
</script>
Output: Parathan
Length of Array : This will return the number of values in the Array.
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
</script>
Output:4
typeof
This will return the Data Type of the variable..
E:g-
<p id="type"></p>
<script>
var person = ["Parathan", "Saravanan", "Varshanan"];
document.getElementById("type").innerHTML = typeof person;
</script>
Output: object
Array.isArray() : This method will check if that variable is an array or not.
<p id="test"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("test").innerHTML = Array.isArray(fruits);
</script>
Output: true
Another way of instanceof array is used to test the array
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits instanceof Array;
</script>
Output: true
No comments:
Post a Comment