views:

161

answers:

3

Hey everyone,

I am creating a gallery plug-in in which I need to figure out the number of elements in a plain javascript object. The following is how I would like to be able to create the gallery.

$.Gallery.create($('#galContainer'), {
    'img1.png': 'http://linktosomewhere/',
    'img2.png': 'http://linktosomewhere/',
    'img3.png': 'http://linktosomewhere/',
    ........
}, optionsObj);

This will put the images into the gallery with the corresponding links to some page when clicked. Currently I am using an array for that second parameter without the links and I am getting the length of the images using images.length. However using the notation above would be ideal for me and I need to be able to tell how many keys there are in this object.

I am aware of this post and a few others saying you can not get the number of elements in the object. If this is indeed the case, do you have any suggestions on another way to setup this function call which will be efficient and easy to use?

Thanks for any help on this!
Metropolis

+2  A: 

The code you see in the other question you linked to is really the only way to do it. Here's how you can create a function to do it:

function count(obj) {
  var i = 0;
  for (var x in obj)
    if (obj.hasOwnProperty(x))
      i++;
  return i;
}
casablanca
You should also declare `x` with `var`. Current version use global `x`.
Oleg
Oops, thanks for pointing that out.
casablanca
Thanks casa, I will definitely add this to my arsenal of functions, and use it later. But I think for this particular instance I would rather not rely on this.
Metropolis
A: 
Object.prototype.count = function()
{
   var c = 0;var i;
   for(i in this){if (this.hasOwnProperty(i)){c++;}};
   return c;
}

Personally I would build your own prototype for Object, you can use MyObject.length but I think its not fully supported by IE.

test reveal that the length variable is unavailable in Objects.

Testcase:

MyObject = {
    a : '0',
    b : '1',
    c : '2'
}
if(MyObject.count() > 5)
{
    $.Gellery.Error('Images','Only 5 images allowed'); //...
}

http://jsfiddle.net/b9Nwv/

RobertPitt
You should also declare `i`,`c` with `var`. Current version use global `i` and `c`.
Oleg
not a major but thanks anyway.
RobertPitt
+1  A: 

Can't you use an array of objects instead?

$.Gallery.create($('#galContainer'), [
    {src:'img1.png', href:'http://linktosomewhere/'},
    {src:'img2.png', href:'http://linktosomewhere/'},
    {src:'img3.png', href:'http://linktosomewhere/'},
    ........
], optionsObj);

You should just add a .src and .href in your code to read it.

The way you designed your dataset as a simple hash is not very flexible for additional attributes(size, categories, selected, etc...)

Mic
Great idea mic! Thanks for the help!
Metropolis