Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 422
ellabeauty Avatar asked Mar 31 '12 01:03

ellabeauty


People also ask

How do you add a property to an array?

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.

Can an array have properties?

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.


2 Answers

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.

like image 85
Kevin Ennis Avatar answered Sep 22 '22 05:09

Kevin Ennis


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 a total 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);.

like image 42
cloudfeet Avatar answered Sep 23 '22 05:09

cloudfeet