在Javascript中向Array对象添加方法?

use*_*650 13 javascript

是否可以在javascript中向array()添加方法?(我知道原型,但我不想为每个数组添加一个方法,特别是一个).

我想这样做的原因是因为我有以下代码

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

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

var importantVars = drawChart();

updateChart(importantVars);
Run Code Online (Sandbox Code Playgroud)

我希望能够做到这样的事情:

var chart = drawChart();<br>
chart.redraw();
Run Code Online (Sandbox Code Playgroud)

我希望有一种方法可以将方法附加到我正在返回的内容中drawChart().有办法吗?

jef*_*eff 36

数组是对象,因此可以包含诸如方法之类的属性:

var arr = [];
arr.methodName = function() { alert("Array method."); }
Run Code Online (Sandbox Code Playgroud)


jja*_*man 8

是的,容易做到:

array = [];
array.foo = function(){console.log("in foo")}
array.foo();  //logs in foo
Run Code Online (Sandbox Code Playgroud)


Jus*_*ner 5

只需实例化数组,创建一个新属性,然后为该属性分配一个新的匿名函数即可。

var someArray = [];
var someArray.someMethod = function(){
    alert("Hello World!");
}

someArray.someMethod(); // should alert
Run Code Online (Sandbox Code Playgroud)