如何在JavaScript中计算函数的自变量数量,包括可选自变量? [英] How to count number of arguments of a function, in javascript, INCLUDING optional arguments?

查看:118
本文介绍了如何在JavaScript中计算函数的自变量数量,包括可选自变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我在javascript中具有以下功能:

For example, if I have the following function in javascript:

var f1 = function(a, b, c) {}
console.log(f1.length); // 3

但是使用此功能,输出是不同的:

But with this function, the output is different:

var f2 = function(a, b, c = 6) {}
console.log(f2.length); // 2

如何计算f2包括可选参数的参数数量?

How do I count number of arguments of f2 INCLUDING optional arguments?

推荐答案

好吧,虽然有些混乱,但是我认为这应该可以涵盖大多数边缘情况.

Well, it's a bit of a mess but I believe this should cover most edge cases.

通过将函数转换为字符串并计算逗号,但忽略字符串,函数调用或对象/数组中的逗号来工作.我想不出哪一种方案无法返回正确的金额,但是我敢肯定有一种方案,所以这绝不是万无一失的,但在大多数情况下应该可以解决.

It works by converting the function to a string and counting the commas, but ignoring commas that are in strings, in function calls, or in objects/arrays. I can't think of any scenarios where this won't return the proper amount, but I'm sure there is one, so this is in no way foolproof, but should work in most cases.

function getNumArgs(func) {
  var funcStr = func.toString();
  var commaCount = 0;
  var bracketCount = 0;
  var lastParen = 0;
  var inStrSingle = false;
  var inStrDouble = false;
  for (var i = 0; i < funcStr.length; i++) {
    if (['(', '[', '{'].includes(funcStr[i]) && !inStrSingle && !inStrDouble) {
      bracketCount++;
      lastParen = i;
    } else if ([')', ']', '}'].includes(funcStr[i]) && !inStrSingle && !inStrDouble) {
      bracketCount--;
      if (bracketCount < 1) {
        break;
      }
    } else if (funcStr[i] === "'" && !inStrDouble && funcStr[i - 1] !== '\\') {
      inStrSingle = !inStrSingle;
    } else if (funcStr[i] === '"' && !inStrSingle && funcStr[i - 1] !== '\\') {
      inStrDouble = !inStrDouble;
    } else if (funcStr[i] === ',' && bracketCount === 1 && !inStrSingle && !inStrDouble) {
      commaCount++;
    }
  }

  // Handle no arguments (last opening parenthesis to the last closing one is empty)
  if (commaCount === 0 && funcStr.substring(lastParen + 1, i).trim().length === 0) {
    return 0;
  }

  return commaCount + 1;
}

以下是我尝试过的一些测试: https://jsfiddle.net/ekzuvL0c/

Here are a few tests I tried it on: https://jsfiddle.net/ekzuvL0c/

这篇关于如何在JavaScript中计算函数的自变量数量,包括可选自变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆