What is an array?
Array is a collection of similar data items that can be stored under a common name. For example ,we have books of english,science,maths .Here the common name is books ,where english,science,maths are same items which can be come under the name of books.Example of array in javascript:
Copy and paste the below code in notepad and save as index.html .Then open with the browser.
<p id="abc"></p>You will get output as maths
<script>
var books= ['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books[2];
</script>
General format of array:
What will happen adding comma at the end of maths?
It just show the last array value,(i.e) maths. But it is not good thing to use like this.Sometimes it may affect the output.So it is best to use comma correctly.
What will happen if you use document.getElementById("abc").innerHTML = books[3]; for the above example?
It just show the output undefined .
What will happen if you use parenthesis () instead of using square brackets [] in arrays?
Consider the below example,
For the above example ,it took only maths and shows the letter t .
<p id="abc"></p>
<script>
var books=('english' , 'science','maths');
document.getElementById("abc").innerHTML = books[2];
</script>
How to use array length property?
You can also calculate and display how much array elements we are using with the array length property.Use the below code,
<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books.length;
</script>
You will get the output 3 . Because we had english, science and maths . Keep in mind the array numbering starts from 0,1,2 but when we use for counting purpose the total is 3 .
How to find which items in which array element?
We can use of indexOf to find items in which array element.Keep in mind javascript is case-sensitive so we must use indexOf and not indexofCopy and paste the below code in notepad and save as index.html .Then open with the browser.
You will get output 2. (i.e ) it shows maths in the array element of array[2].
<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books.indexOf("maths");
</script>
How to Display items in array element with ascending order?
Copy and paste the below code in notepad and save as index.html .Then open with the browser.Now it will show the output of english,maths,science .
<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books.sort();</script>
0 comments :
Post a Comment