+ 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?
5 Respuestas
+ 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);
+ 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.
+ 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" ] );
+ 2
Thank you very much! It is working 😀
- 1
How do we add array elements