Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a method to Array object in Javascript?

Tags:

javascript

Is it possible to add a method to an array() in javascript? (I know about prototypes, but I don't want to add a method to every array, just one in particular).

The reason I want to do this is because I have the following code

function drawChart()
{
    //...
    return [list of important vars]
}

function updateChart(importantVars)
{
    //...
}

var importantVars = drawChart();

updateChart(importantVars);

And I want to be able to do something like this instead:

var chart = drawChart();<br>
chart.redraw();

I was hoping there was a way I could just attach a method to what i'm returning in drawChart(). Any way to do that?

like image 348
user1167650 Avatar asked Jul 10 '12 21:07

user1167650


People also ask

How do you add a method to an array of objects?

Method 3: unshift() method The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method.

Can you put methods in an array?

You Cant. However you can create a functional interface and then use lambdas to populate the array. Then you can create a reference to the interface and assign it to a random implementation from the array.

How do you add a method to an object?

Adding a method to the object Adding a method to a javascript object is easier than adding a method to an object constructor. We need to assign the method to the existing property to ensure task completion.


2 Answers

Arrays are objects, and can therefore hold properties such as methods:

var arr = [];
arr.methodName = function() { alert("Array method."); }
like image 93
jeff Avatar answered Oct 10 '22 19:10

jeff


Yep, easy to do:

array = [];
array.foo = function(){console.log("in foo")}
array.foo();  //logs in foo
like image 21
jjathman Avatar answered Oct 10 '22 19:10

jjathman