tags:

views:

1218

answers:

6

Hello All I am using javascript associative array like:

var testarray = [];
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

I am also using jquery alongside. How can I check length of this associative array using jquery or any other method? Basically i want to check whether this array is empty or not.

Thank you.

A: 

EDITED:

Take a look at, is the same question: http://stackoverflow.com/questions/5223/length-of-javascript-associative-array

Keyne
No, that's for numeric indexes.
T.J. Crowder
not going to work.
Pointy
That will show the value 0.
Guffa
It is showing zero (0) in length. I think length property does not work in case of associative array.
Prashant
@Prashant: The length doesn't work because there isn't really any associative array in Javascript. You are just putting properties in an array object just as you can do with any object.
Guffa
Yes, it is. Sorry for that, I did not notice that.
Keyne
@Guffa: *"The length doesn't work because there isn't really any associative array in Javascript."* Yes, there is: **All** JavaScript objects are associative arrays. Using `length` doesn't work here because it's defined as "one greater than the greatest *numeric* property name".
T.J. Crowder
@T.J.: Well, you can say that. On the other hand saying that all objects are arrays can be more confusing that explanatory.
Guffa
@Guffa: When I was learning JavaScript, it was a hugely useful thing for me to learn.
T.J. Crowder
+4  A: 

There's no direct "length" or "size" call, you have to test the keys available within the object.

Note that all JavaScript objects are associative arrays (maps), so your code would probably be better off using a generic object rather than an array:

var testarray = {}; // <= only change is here
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

You can find out what the keys are in an object using for..in:

var name;
for (name in testarray) {
    // name will be 'one', then 'two', then 'three' (in no guaranteed order)
}

...with which you can build a function to test whether the object is empty.

function isEmpty(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
}

As CMS flagged up in his answer, that will walk through all of the keys, including keys on the object's prototype. If you only want keys on the object and not its prototype, use the built-in hasOwnProperty function:

function isEmpty(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}
T.J. Crowder
And also don't forget about `hasOwnProperty()` to don't count properties from prototype.
MBO
probably should use the "hasOwnProperty" trick, something I wouldn't know about had I not become addicted to stackoverflow :-)
Pointy
@MBO, Pointy, and (indirectly) CMS: Quite right, added!
T.J. Crowder
+4  A: 

You shouldn't use an array to store non-numeric indexes, you should use a simple object:

function getObjectLength (o) {
  var length = 0;

  for (var i in o) {
    if (Object.prototype.hasOwnProperty.call(o, i)){
      length++;
    }
  }
  return length;
}

Edit: Since you are using jQuery and you want to check if the object is "empty", the 1.4 version introduced the $.isEmptyObject

if ($.isEmptyObject(obj)) { 
  //...
}
CMS
ooh I like that you get "hasOwnProperty" from the Object prototype :-)
Pointy
You shouldn't use an array to store *only* non-numeric indexes (as I said in my answer), but I don't see any issue with *also* storing non-numeric information on arrays you're using for their "normal" purpose.
T.J. Crowder
Why not use the `hasOwnProperty` on `o` itself? To avoid it having possibly been replaced?
T.J. Crowder
@T.J. Crowder: Yes, safety first, otherwise `getObjectLength ({hasOwnProperty: 'foo'})` will make the function throw a `TypeError`...
CMS
@CMS: Thanks, I figured. I think I'd defer to the object author, though. If they have a good reason for overriding it, I should respect it (even if that means they blow things up for themselves).
T.J. Crowder
A: 

You don't really have an array there, so I'd avoid initializing it as such:

var testNotArray = { };
testNotArray['one'] = 'something';
// ...

Now this is inherently dangerous, but a first step might be:

function objectSize(o) {
  var c = 0;
  for (var k in o) 
    if (o.hasOwnProperty(k)) ++c;
  return c;
}

Again, there are a million weird ways that that approach could fail.

Pointy
A: 

You could calculate the length like below:

var testarray = {}; // Use a generic object to store non-numeric indexes not an array
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';
var count = 0
for each(key in testarray)
 count = count + 1
alert(count); // count contains the number of items in the array
ardsrk
A: 

You can loop through the properties to count them:

var cnt = 0;
for (i in testarray) cnt++;
alert(cnt);

Note that the for (... in ...) will also loop items added by a prototype, so you might want to count only the items added after that:

var cnt = 0;
for (i in testarray) if (testarray.hasOwnProperty(i)) cnt++;
alert(cnt);

If you just want to check if there are any properties, you can exit out of the loop after the first item:

var empty = true;
for (i in testarray) if (testarray.hasOwnProperty(i)) { empty = false; break; }
alert(empty);
Guffa