Arrays have a "length" property by default.
Can I add custom properties to them?
Without having to make them objects.
We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value. according to the console log.
Arrays also have built-in properties, such as array. length . The length property carries an integer value that denotes the length of an array. In general, built-in properties can be frequently found in predefined JavaScript objects like arrays.
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);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With