Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Get the names of function parameters from outside of the function

I want to know if it possible to get the names (not the values) of the function parameters from outside of a function, either with a native JavaScript function/method or something custom.

// function parameters cat, dog, bird
function foo(cat, dog, bird) {};

// now access these names from outside the function, something like (pseudocode)
foo.getFunctionParameters(); 

or

getFunctionParameters(foo);

Which would log

['cat', 'dog', 'bird']

The reason: I have an object that has a values functions. These functions have different function parameters. I must loop through this Object and execute the function. I do not want to pass a key with each Object that contains the function, telling me which function parameter to pass (via an if...else). I'd simply create an Object with my possible function parameters and the use the actual function parameters to access the needed values.

const someArray = [
    {
        foo: [
            {
                function: (cat, dog) => {...},
                otherKeys: otherValues,
            },
            {
                function: (apple, orange) => {...},
                otherKeys: otherValues,
            },
            {
                function: (cat, apple) => {...},
                otherKeys: otherValues,
            },
            ...
        ],
        ...
    }
]

Then I'd simply construct an object with the possible function parameters

const possibleFuncParams = {
    cat: 'Sweet',
    dog: 'More a cat person',
    apple: 'I like',
    orange: 'not so much',
    ...
}

And then use the function paramaters coming back from getFunctionParameters() to access the object (something like this):

const keys = getFunctionParameters();
possibleFuncParams[keys[0]];
possibleFuncParams[keys[1]];

What I do not want to do is

const someArray = [
    {
        foo: [
            {
                function: (cat, dog) => {...},
                otherKeys: otherValues,
                keyToSelectFuncParam: 'animals'
            },
            {
                function: (apple, orange) => {...},
                otherKeys: otherValues,
                keyToSelectFuncParam: 'fruits'
            },
            {
                function: (cat, dog) => {...},
                otherKeys: otherValues,
                keyToSelectFuncParam: 'mixed'
            },
            ...
        ],
        ...
    }
]

And then

if(keyToSelectFuncParam === 'animals') {
    foo.functio('Sweet', 'More a cat person');
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I got this by googling... try it

// JavaScript program to get the function
// name/values dynamically
function getParams(func) {

  // String representaation of the function code
  var str = func.toString();

  // Remove comments of the form /* ... */
  // Removing comments of the form //
  // Remove body of the function { ... }
  // removing '=>' if func is arrow function
  str = str.replace(/\/\*[\s\S]*?\*\//g, '')
    .replace(/\/\/(.)*/g, '')
    .replace(/{[\s\S]*}/, '')
    .replace(/=>/g, '')
    .trim();

  // Start parameter names after first '('
  var start = str.indexOf("(") + 1;

  // End parameter names is just before last ')'
  var end = str.length - 1;

  var result = str.substring(start, end).split(", ");

  var params = [];

  result.forEach(element => {

    // Removing any default value
    element = element.replace(/=[\s\S]*/g, '').trim();

    if (element.length > 0)
      params.push(element);
  });

  return params;
}

// Test sample functions
var fun1 = function(a) {};

function fun2(a = 5 * 6 / 3, // Comment
  b) {};

var fun3 = (a,
  /*
   */
  b, //comment
  c) => /** */ {};

console.log(`List of parameters of ${fun1.name}:`, getParams(fun1));
console.log(`List of parameters of ${fun2.name}:`, getParams(fun2));
console.log(`List of parameters of ${fun3.name}:`, getParams(fun3));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda