Search code examples
jqueryarraysis-empty

Array length coming back as undefined when including key and value


JQUERY

var a = {};
$('#individual_users_result').find("li").each(function() {
    var added_domains = $(this).attr('data-id');
    var added_domains_text = $(this).text().trim();
    a[added_domains] = added_domains_text;
})

I am creating an array where I am including the key and value. I am trying to determine if the array is empty or not. I have confirmed using console.log(a) the results and it is producing exactly what I need.

When I use this to find out if the array is not empty I get undefined on a.length

if (a.length !== 0) {
    alert(a.length)
}

If I change this

a[added_domains] = added_domains_text;

to this

a = added_domains_text;

Then I get a length of 39

What is it about me adding the key value when producing the array causing my code to show the length as undefined?


Solution

  • Should be: var a = [];for an empty array not {}

    Example:

    var a = [item1, item2, item3];