ruben450
ruben450

Reputation: 140

Javascript array containing arrays but length is 0

var food = ["fruit=apple", "fruit=banana", "drink=cola"];
var vars = [];
for(var i = 0; i < food.length; i++)
{
    var key = food[i].substring(0, food[i].indexOf("="));
    if (vars[key] == undefined){
        vars[key] = [];
    }
    vars[key].push(food[i].toLowerCase().split("=")[1]);
}
console.log(vars);
console.log(vars.length);

The output from the above code will output this. But the problem is that the length: 0. I don't understand how that is even possible, because you can clearly see that the array containing [fruit: Array(2), drink: Array(1)]. But still it says length: 0;

The output of vars and vars.length

I want to loop through the vars array with a for loop, but I can't because I cannot use the vars.length in my for loop.

Or maybe there is a other way to loop through the vars anny suggestions are welcome.

Upvotes: 0

Views: 103

Answers (1)

hsz
hsz

Reputation: 152216

You are using your vars array as an object. Arrays don't have literal keys. With your approach, you can count your values using:

Object.values(vars).length

Upvotes: 2

Related Questions