Hi Guys,
So for the project I am working on I am using both PHP and Javascript.
Now I got a habit of using count() method in PHP for array to count the number of element in an Array.
You can use length property of an Array in Javascript but I like it the PHP way so then I wrote these few lines of code to accomplish that
So traditionally in PHP we use something like this
PHP Pseudo Code
// do this } else { // do that }
This is A way to use count method but its used at many different places for different use cases.
Now lets see whats the Javascript equivalent
Advertisement
Javascript Count() method
So say we have a Javascript array as shown below
var myArray = [1,2,3,4,5]
I can get the count of array elements by simply doing this
console.log(myArray.length)
Above will print 5
Thats good. I mean there is no real advantage of having a count() method but lets see how to do a count() method for an array. Now just return a length property may just not be enough to get what you want (an actual count of elements)
Array.prototype.count = function() { return this.length; };
A much better approach would be the one below and the one that I will use.
Array.prototype.count = function() { var cnt = 0; for(k in this) { if(this[k] != undefined) { cnt++; } } return cnt>0?cnt-1:0; };
Above approach will handle cases like this one
mas = []; mas[23] = 23; console.log(mas.count()); // will return 1 rather than 24
Now when you do this
console.log(myArray.count());
Above will print 5
For me I don’t think that length in Javascript is true length of an array. But in most cases it does the trick.
You can do the same for extending default behaviour for any known Javascript class.
I hope this helps
Cheers
P.S. : Its always a good idea to keep your custom methods in your standalone object rather to extend native objects. That’s my opinion.
Advertisement





JC WordPress Coupon Revealer Plugin Pro License
Australian Street Names with City, State and Display Names only, Single Server License
Recent Comments