Are objects similar to arrays?

5

Objects are arrays in JavaScript? I have difficulty understanding how this is possible:

var obj = {
   title: 'some value'
}
console.log(obj['title']); // some value

In my conception the use of brackets is only possible in lists to pass a direct index or have an incremental variable to go through all the objects.

How is this possible? When I access ['title'] does it go through all the keys ( Object.keys ) of the object until it finds the requested key or goes straight to the index? >     

asked by anonymous 08.04.2016 / 19:20

3 answers

6

I've answered almost every question here .

There is a question that deals with the subject general (I suggest reading for full details). In short, JS objects are actually arrays (associative). Then each member of the object in the background is a key to the array . When you access obj.title , in the background you are accessing obj["title"] . It is essentially syntactic sugar.

This is used by several dynamic languages .

The exact implementation of this depends on the engine that is being used, but I can guarantee that everyone uses some hash table so that the search for the keys occurs in complexity O (1) - constant time. So you can say that it goes straight to the "index", although it has an earlier step.

var meuObjeto = {
a: 1,
"b": 2
};
for (var chave in meuObjeto) {
  meuLog("key " + chave + "; value " + meuObjeto[chave]);
}
meuLog("tipo: " + typeof(meuObjeto));

function meuLog(msg) {
  div = document.body;
  div.innerHTML = div.innerHTML + '<p>' + msg + '</p>';
}
    
08.04.2016 / 19:32
6

TL; DR: Yes , generically - with some poren.

Long answer: All prototypical javascript types ( Boolean , Number , String , Function , Array , Date , RegExp ) are implementations that expand the behavior of Object .

In the case of Array , whose focus is numerical indexing of data, methods like push() and properties like length are implemented.

However, you can still use the prototypical functions of Object, such as indexed properties:

var myArray = Array();

myArray['A'] = "Athens";
myArray['B'] = "Berlin";

console(myArray.length); // Resultado será zero

The value of length in the above example is zero because the value was not added using the implementation present in the prototype array - instead it was added to the object >.

Source: link

    
08.04.2016 / 19:31
3

No, but they have some similarities. Although you can access properties in the same way, the methods each have are different.

Example:

a = {};
b = [];
console.log(a.forEach); //undefined
console.log(b.forEach); //function forEach(){ ... }
    
08.04.2016 / 19:30