1

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?

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
Ranger 22
  • 415
  • 4
  • 19

2 Answers2

4

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?

Community
  • 1
  • 1
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • Thanks, man. It's clear for me now. But how can I loop A's sub values if A is an object? – Ranger 22 May 10 '17 at 10:25
  • Just found the method myself, http://stackoverflow.com/questions/921789/how-to-loop-through-plain-javascript-object-with-objects-as-members – Ranger 22 May 10 '17 at 10:28
  • @Ranger22 Apply the loop in sub value using [`Object.keys(A)`](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwirz6SMkeXTAhUTSo8KHXfCC6YQFgglMAA&url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys&usg=AFQjCNHxNfTCTiOC4tCXBdJjQ2o4l76MOw) its create the array of keys only .[`Object.values(A)`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values) its create the array of values of the Object.Apply the loop from this – prasanth May 10 '17 at 10:39
  • Good .http://stackoverflow.com/questions/921789/how-to-loop-through-plain-javascript-object-with-objects-as-members in this more no of the possible loop function .You could choose any on of this from – prasanth May 10 '17 at 10:41
1

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