In Javascript (and potentially other languages, but I don’t remember any) there is a type of data Array
who owns a property length
(indicating its size), the ability to have its individual elements accessed by numeric indexes (x[0]
), and various other methods belonging to the type.
However, except for a few small details (more on that below), there is no significant difference between an array and a "normal" object. If you create an object of type:
var objeto = { "0":"foo", "1":"bar", "2":"baz", length:3 };
You can use it in many situations as if it were a native array:
for ( var i = 0 ; i < objeto.length ; i++ )
console.log(objeto[i]);
What are you can’t is to use native methods of Array
- since this object does not have this type as a prototype (by default - if you want, you can give this prototype to it):
objeto.forEach(function() { ... }); // undefined não é um método
Another difference is that in an array, adding new elements updates your property length
automatically, while in an ordinary object this does not happen:
var arr = [];
$("#saida").append("<p>" + arr.length + "</p>");
arr[0] = 10;
$("#saida").append("<p>" + arr.length + "</p>");
var obj = { length: 0 };
$("#saida").append("<p>" + obj.length + "</p>");
obj[0] = 10;
$("#saida").append("<p>" + obj.length + "</p>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="saida"></div>
Because there is no significant difference, it is very common for a Javascript library to allow programmers to use their objects as arrays, even when it is inconvenient to use a "real" array. In this case, it is said that the object is "like an array", or in English "array-like". The best example I have of a array-like is the "jQuery object":
var ps = $("p"); // Selecionei todos os elementos p
ps.html("foo"); // O retorno é um objeto jQuery, com suas próprias funções
for ( var i = 0 ; i < ps.length ; i++ ) // Mas também posso usá-lo como se fosse um array
ps[i].innerHTML = "foo";
Know if an object is array or array-like is only important when it is used in a specific way for arrays. Often to allow a wider range of input values (i.e. without limiting to objects of the type Array
) if you choose to program in a way that works for both arrays and array-Likes. The for
above was an example. Another would be the use of the functions of Array
explicitly referenced in their prototype:
Array.prototype.forEach.call(objeto, function() { ... }); // Funciona em ambos os casos
Or, to add an element and ensure that the length
be updated:
var objeto = { length:0 };
Array.prototype.push.call(objeto, 10); // Depois dessa chamada, length é 1
P.S. It is also good to note that in Javascript all properties are textual. Even in an object of the type Array
, when you do:
var arr = [1,2,3];
arr[1] = 4;
Internally this is represented as if it were:
var arr = Object.create(Array.prototype, { "0":1, "1":2, "2":3, "length":3 });
arr["1"] = 4;
Other languages may have different implementations, and different considerations regarding what is or is not a array-like (or even not allow array-Likes at all). Formally speaking, for an object to be considered X-like it must have an implicit interface that is compatible to some extent with the "X" type. That is, even if it does not belong to the class, and that class does not have an explicit contract, that object still fulfills its implicit contract sufficiently to be used in practice as an instance of that type.
Needless to say, this concept only makes sense in languages with dynamic typing or Duck-Typing - if the typing is static, the only thing that can be used in place of an array is an array subtype (which, by the inheritance relation "is an" array, does not "look like" an array).
What is a prototype?
– ropbla9
@ropbla9 To understand prototypes (and prototypic inheritance), I suggest the question "How prototypes work in Javascript?" (to my knowledge, JS is the only popular language that uses this type of object orientation). About your previous comment, string is array-like yes, as it has
length
and its characters (substrings, in fact) are accessed by numeric index. Already any object would not be - because it is necessary the propertylength
at a minimum (and if the object is not used sequentially, it is not works as array-like).– mgibsonbr
So every JS object is not array-like? Even the Array, being arraylike only its primitive data (array)? Only declared objects and DOM are array-Likes? correct?
– ropbla9
Friend, I need to chat with you. Would it be possible?
– ropbla9
@ropbla9 Are you still there? I was offline and did not see your answer, was bad! As for your comment, be or not array-like is more a question of functionality: if an object implements a list, but does so through a chaining (e.g..:
{car:1, cdr:{ car:2, cdr:{ car:3, cdr:null }}}
) cannot access this object using indexes. If it uses something else instead oflength
(ex.:{"0":1, "1":2, "2": 3, tamanho:3}
) a function that was done expecting an array will not work on it. Etc. Be array-like means "if I pass it to a function that expects an array, it will work". Only.– mgibsonbr
I have been studying JS for 5 months and these concepts are still complex for me (first contact with programming). I really want to learn more about DOM manipulation, I know q would be softer with JQ, but I want to learn pure JS. I was looking to buy the full JS course from Devmedia. What do you think?
– ropbla9
I find it difficult to opine, I do not know this course, and as long as I learned JS (by the way, "I was learning" little by little...) I do not know good and updated material. Have you checked in the javascript tag wiki? At the end there are some recommendations of books and online material, made by other users.
– mgibsonbr