简体   繁体   中英

javascript length about an empty object

<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.

  1. 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.

  2. Why I can set it as the way of array? (by [] operator such as map[5] = 3).

  3. Why the length of map is undefined ?

  4. Could I deem map as a hash table of JavaScript?

Thanks.

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. :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM