JavaScript – Count Array

 
Do you like this story?

I’m a PHP man myself however I’ve been playing around with JavaScript a lot lately since I’ve been creating the CRM for our web design company…

A cool little trick I learn’t today (I couldn’t find the answer easy enough in Google so I just figured it out myself) is how to count an array using JavaScript.

In PHP you’d simply write:

<?php
$myarray = array(‘red’, ‘green’, ‘blue’);
echo count($myarray);
?>

This is how you do it in JavaScript:

<script language=”javascript” type=”text/javascript”>
var myarray = new Array(‘red’, ‘green’, ‘blue’);
document.write(myarray.length);
</script>

Hopefully that helps anyone in the same predicament as I was :)

 

15 Comments | Have Your Say..

» Subscribe To These Comments

  1. qwakki
    17.04.08

    Thanks alot :)

  2. Magnus
    02.05.08

    Helped me. Thanks.

  3. Joris
    24.06.08

    I was looking for this! tnx!

  4. Lagon666
    01.08.08

    THANKS, THIS POST SOLVED MY PROBLEM.

  5. tobacamp
    26.09.08

    thank you very much

  6. Hikmat
    22.01.09

    Thank you. This lil bit helped me a lot. Loves these little snippets of code-guides.

  7. sanjit
    19.02.09

    this give the no of character in an array

    var myCars=”sanjitkumarmishra”;
    //len = myCars.length;

    var myarray = new Array(‘red’, ‘green’, ‘blue’);
    var lens = myarray.join();
    len = lens.length;
    var g=0;
    for(i=0;i

  8. Erik
    28.02.09

    Thx a lot!

  9. Ignas
    31.03.09

    Thanks this helped me.

  10. Mohammed Isma
    06.04.09

    Thanks a bunch man. I’ve been looking around for a while. This helps a LOT.
    Cheers.

  11. Timothy
    12.10.10

    hey thanks for the tip!

  12. thx, this is the stuff I was searching for :)
    greeeetings, yeah

  13. Mike
    04.11.10

    Thanks

  14. Quit
    21.02.11

    Thanks a lot worked for me Info

  15. SmarT
    24.02.11

    It only works if you have numbered 0 to n array keys.
    If you have an array like:

    var arr = new Array();
    arr[12] = ‘one’;
    arr[34] = ‘two’;
    alert (arr.length); // would give you 34 instead of 2

    In that case I didn’t find anything besides:
    var cnt;
    for (k in arr) { cnt++; }

Leave a Reply

Note: If you would like your photo to appear beside your comment, you will need to add your photo here: www.gravatar.com.