Add a property to a JavaScript array
Arrays have a "length" property by default.
Can I add custom properties to them?
Without having to make them objects.
Sure.
var arr = [1,2,3,4,5];
arr.prop = 'value';
Arrays are already objects in JavaScript -- they just have some extra features and a special literal syntax.
As other answers state, it's perfectly possible, because arrays in JavaScript are just objects. However, there is still the a question of whether it's a good idea or not.
That's a "coding style" question, so it's hard to say objectively, but Douglas Crockford doesn't have a problem with it (at least in some cases). In JavaScript: The Good Parts, he actually uses the example of adding a "total" method to an array.
Because an array is really an object, we can add methods directly to an individual array:
// Give the data array a total function data.total = function () { return this.reduce(add, 0); }; total = data.total(); // total is 108
Since the string
'total'
is not an integer, adding atotal
property to an array does not change its length.
(p62, Crockford's "JavaScript The Good Parts", found on Google Books)
However, it is worth mentioning that these extra properties are not included in JSON serialisation, and would be thrown away if you do anything like arr = arr.slice(1);
.