How to add a method to the prototype of an array in JS? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to add a method to the prototype of an array in JS?

I have a dataset as an array with objects and I want to add a new method (function that calculate some extra values to a dataset) to the prototype of the array. Is that possible?

7th Feb 2017, 6:41 PM
3TW3
3TW3 - avatar
5 Answers
+ 4
If by "as an array" you mean that you have defined an object structure to handle a list of objects, like: var args; // a fake content var var myDataSet = { 'customProperty':args, 'customList':[] } ... or more verbosely: var myDataSet = function(args) { this.customProperty = largs; this.customList = [ ]; } ... you can change it in a JS pseudo-class: var MyClass = function(args) { this.customProperty = largs; this.customList = [ ]; this.customMethod = function(params) { /* function body definition */ }; } ... and use: var myDataSet = new MyClass(args); var params; // another one fake content var myDataSet.customMethod(params);
8th Feb 2017, 2:38 AM
visph
visph - avatar
+ 3
You actually can, but rather than modifying it, you can write a mini library that abstracts the functions you wish. Personally, when I use a pre-existing feature, I want to be sure I'm using that thing as it is, except where I need to compensate for compatibility issues with older browsers. Anyways, just add the new method on the Array prototype and you're golden.
8th Feb 2017, 2:45 PM
John
John - avatar
+ 3
@Mayson: var myArray1 = [ ]; myArray1.push( "text" ); myArray1.push( 42 ); myArray1.push( [ "nested" , "array" ] ); var myArray2 = new Array(); myArray2.push( "text" ); myArray2.push( 42 ); myArray2.push( [ "nested" , "array" ] ); var myArray3 = [ "text", 42, [ "nested", "array" ] ]; var myArray4 = new Array( "text", 42, [ "nested", "array" ] );
9th Feb 2017, 6:57 PM
visph
visph - avatar
+ 2
Thank you very much! It is working 😀
8th Feb 2017, 4:34 PM
3TW3
3TW3 - avatar
- 1
How do we add array elements
9th Feb 2017, 5:55 PM
Mayson
Mayson - avatar