2

lets say I have array of functions such as [ function f1{}, function f2{}] and I know that the function I want to get a reference too is called "f2", so that I can remove it from the array, how would I go about it? I tried using the object that contains an array like

ctrl.$parsers["f2"] but it does not return anything. Is this possible?

1
  • Why not have your functions numbered based on the index of your array then you could access them easier. So for example if f1 was your first function you could take the string "f1" and get the last number then subtract 1 from it and use that as the array index Commented Nov 22, 2013 at 20:15

3 Answers 3

2

You could iterate over the array and inspect the function's name attribute:

function getNamedFunction(arr, name) {
    for (var i = 0, l = arr.length; i < l; i++) {
        if (arr[i].name === name) {
            return arr[i];
        }
    }
}

But Function#name is not a standard property:

This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

A better (more compatible) approach would be to store your functions in an object:

var functions = {
   'f1': f1,
   'f2': f2,
};

and access it with

functions['f1']
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the filter method of the Array to select functions with a specific name

var myFunctions = [
    function a(){ alert(1); },
    function b(){ alert(2); },
    function c(){ alert(3); }
];

var someName = 'c'; // name of function to search for

// filter array checking the name property of each function in the array
var someFunction = myFunctions.filter(function(f){ 
    return f.name == someName; 
})[0]; // get the first function from the resulting filtered array

someFunction(); // alerts '3'

Comments

1

Use the name prop and try this

for (var i=0;i<arr.length;i++)
{
 if (arr[i].name=='f2')....
}

Later you can use splice to remove the element.

array.splice(index, 1); ( returns the same array instance)

p.s.

This feature is non-standard

So what can you do ?

you can do this :

var g=[function f2(){},function f4(){}];

for (var i=0;i<g.length;i++)
{
  var m=g[i].toString().match(/function\s+(\w+)/i);

  if (m  && m[1]=='f4') alert(i);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.