How to use arrays in the javascript?



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.


javascript-arrays


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>
<script>
var books= ['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books[2];
</script>
You will get output as maths
General format of array:

array-javascript

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,

<p id="abc"></p>
<script>
var books=('english' , 'science','maths');
document.getElementById("abc").innerHTML = books[2];
</script>
For the above example ,it took only maths and shows the letter t .

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 indexof
Copy and paste the below code in notepad and save as index.html .Then open with the browser.



<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books.indexOf("maths");
</script>
You will get output 2. (i.e ) it shows maths in the array element of array[2].

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.


<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books.sort();</script>
Now it will show the output of english,maths,science .
Print Friendly and PDF
SHARE

About me

Hi. I am interested in blogging.And sometimes play with webdesign,web development,domain sale,designing logo and more.

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Pages