Reputation: 529
<p style="line-height: 18px; font-size: 18px; font-family: times;">
Click "<i>Load samples</i>" to view and edit more JS samples.<br>
<br>
Labyrinth generated with JavaScript:<br><br>
<script>
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
console.log(sample.length);
var map = {};
map[5] = 3;
console.log(map.length);
</script>
</p>
Hi all:
I am a New hand in JavaScript and much more familiar to C(C++).
I tested the code above & cannot figure out the meaning of map.
What's the difference if I declare:
A. map = [];
B. map = {};
way A seems to be an empty array but B to be an empty object.
Why I can set it as the way of array? (by [] operator such as map[5] = 3).
Why the length of map is undefined?
Could I deem map as a hash table of JavaScript?
Thanks.
Upvotes: 2
Views: 615
Reputation: 343
In array, map[5]
, the 5
here is index
, represent the 6th
element in the array and it has value of 5
, that means you already have 5 elements created before, just values are undefined
,
In object, map[5]
, the 5
here is key, doesn't mean there are other elements created, so the length is 1
Upvotes: 1
Reputation: 167220
Arrays are set of data, identified by consecutive indexed data. While, objects are totally different. They have multiple key value pairs. So, arrays are solely by their indices. Objects are solely by their keys.
var map = [];
map [5] = 5;
console.log(map.length);
The above gives 6
as length because, the consecutive values 0
till 5
are not defined.
While, on the other hand, objects have keys. So to find the length of the objects, we need to use Object.keys
function, which will get all the keys in an array.
var map = {};
map[5] = 5;
console.log(Object.keys(map));
console.log(Object.keys(map).length);
The type of the key here, 5
will be stored as "5"
(string format). And unlikely to arrays, objects do not have undefined
values. They just store the keys. :)
Upvotes: 3