Add a method to Array object in Javascript?

前端 未结 5 1889
梦如初夏
梦如初夏 2020-12-09 17:40

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

相关标签:
5条回答
  • 2020-12-09 17:43

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

    var arr = [];
    arr.methodName = function() { alert("Array method."); }
    
    0 讨论(0)
  • 2020-12-09 17:48

    Yep, easy to do:

    array = [];
    array.foo = function(){console.log("in foo")}
    array.foo();  //logs in foo
    
    0 讨论(0)
  • 2020-12-09 17:50

    Just instantiate the array, create a new property, and assign a new anonymous function to the property.

    var someArray = [];
    var someArray.someMethod = function(){
        alert("Hello World!");
    }
    
    someArray.someMethod(); // should alert
    
    0 讨论(0)
  • 2020-12-09 18:02
    var arr = [];
    arr.methodName = function () {return 30;}
    alert(arr.methodName);
    
    0 讨论(0)
  • 2020-12-09 18:04
    function drawChart(){
    {
        //...
        var importantVars = [list of important variables];
        importantVars.redraw = function(){
            //Put code from updateChart function here using "this"
            //in place of importantVars
        }
        return importantVars;
    }
    

    Doing it like this makes it so you can access the method directly after you receive it.
    i.e.

    var chart = drawChart();
    chart.redraw();
    
    0 讨论(0)
提交回复
热议问题