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;
}