Reputation: 445
Here is the code
var A = [];
A['key1'] = 'apple';
console.log(A.length);
console.log(A['key1']);
A.length is 0 in the log.... But I just don't get it, apparently A['key1'] has a value 'apple'. Why A.length is 0?
Upvotes: 1
Views: 1420
Reputation: 55
You are using javascript associative array which don't have the built-in function like length to get the number of properties in the array. So Instead of using length function you can use the following line to get the number of properties in the array.
Object.keys(A).length
Upvotes: 1
Reputation: 22500
Your are define A
is array .Array is not key and value
pair,Object only have key value pair
Check the console.log A
its still empty
var A = [];
A['key1'] = 'apple';//its not added because is a array
console.log(A);
console.log(A.length);
If you need to add key value pair
Define A
as a Object.and find the length using Object.keys(A)
.It will create array of the Object keys
var A = {};
A['key1'] = 'apple';
console.log(A);
console.log(Object.keys(A).length);
console.log(A.key1.length)
Better see the Difference between an array and an object?
Upvotes: 4