Counting objects in an array (Javascript)

Go To StackoverFlow.com

-1

I have an array made of unlimited number of objects. These objects have the same structure. If I console.log my whole array I get something like this:

[object], [object], [object], ecc...

Whenever I push a new object inside of the array I could also implement a counter, or I could just use a normal for loop to count the objects. Isn't there any more efficient way to count all the objects?

Why does array.lenght not work?

2012-04-03 21:38
by Saturnix
why not? you probably just misspelled it (array.lenght ---> array.length) - Eliran Malka 2012-04-03 21:41
I don't see why array.length wouldn't work, can you show an example - Nick Beeuwsaert 2012-04-03 21:41
Do you mean array.length? Could you please provide a code example - Pete 2012-04-03 21:41
JavaScript is spelling-sensitive - Tuan 2012-04-03 21:45
Assuming you only misspelled .length in this post, and not in your code, I would guess you're not using an Array. You might be using an Object accidentally. Or you're literally using Array.length instead of myArrayVariable.length - Ryan P 2012-04-03 21:45


3

array.length returns the number of elements stored inside an array.

2012-04-03 21:43
by Francisc


1

Most javascript engines will implement an efficient .length method for array objects natively. There is no need for you to duplicate their effort.

If you create an array, you can simply access myArray.length to get the length.

Example:

var myArray = [];
myArray.push({ 'id': 1, 'title': 'Who' });
myArray.push({ 'id': 2, 'title': 'What' });
myArray.push({ 'id': 3, 'title': 'Where' });
myArray.push({ 'id': 4, 'title': 'Why' });

alert(myArray.length); //should be 4
2012-04-03 21:44
by Jordan


0

You should be able to use object.length. Consider this example:

x = [[], function() { return ""; }, 3,document.createElement('div')]
alert(x.length);

That prints "4" for me -- try it with your array and it should print out the proper number of objects in the array to your browser window if you're using javascript on the web... (otherwise just print x.length)

Perhaps posting more of your code will help. Oooh, btw, don't use "array.length" but use "x.length" assuming the x is the name or your array.

2012-04-03 21:44
by Kasapo
Ads