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.
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)) {
//...
}
This gives you the length of your associative array:
Object.keys(testarray).length
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With