【问题标题】:How to query the arguments of a javascript function without calling it如何查询javascript函数的参数而不调用它
【发布时间】:2017-07-12 15:57:22
【问题描述】:

给定一个看起来像下面这样的命令队列。 .

var commandQueue = [
        function() {thing(100, 0, shiftFunc)},
        function() {thing(100, 233, shiftFunc)},
        function() {thing(100, 422, shiftFunc)}
];

如何编写一个函数,将commandQueue 作为参数并将第二个参数(索引 [1])的总和返回给队列中的函数而不调用队列中的函数?

【问题讨论】:

    标签: javascript function introspection


    【解决方案1】:

    很遗憾,这是不可能的。 JavaScript 不提供查看函数定义的能力。

    【讨论】:

      【解决方案2】:

      你可以稍微重写一下,然后使用map

      function thing(a, b) {
        return Math.pow(a * b, 2);
      }
      var commandQueue = [
        function() {
          return thing(100, 0);
        },
        function() {
          return thing(100, 233) % 6;
        },
        function() {
          return thing(100, 422) % 6;
        }
      ];
      var commandResults = commandQueue.map(function(a) {
        return a();
      });
      console.log(commandResults);

      【讨论】:

        【解决方案3】:

        您可以使用Function#toString 和正则表达式,用于搜索第一个和第二个逗号之间的值。

        var commandQueue = [
                function() {thing(100, 0, shiftFunc)},
                function() {thing(100, 233, shiftFunc)},
                function() {thing(100, 422, shiftFunc)}
        ];
        
        console.log(commandQueue.reduce(function (r, a) {
             return r + +((a.toString().match(/,\s*(\d+),/) || [])[1] || 0);
        }, 0));

        【讨论】:

          【解决方案4】:

          你可以这样做:

          const sum = commandQueue.reduce((acc, val) =>
            Number(val.toString().split(',')[1]) + acc, 0);
          console.log(sum);

          【讨论】:

            【解决方案5】:

            var commandQueue = [
                function() {thing(100, 0, shiftFunc)},
                function() {thing(100, 233, shiftFunc)},
                function() {thing(100, 422, shiftFunc)}
            ];
            
            
            function getThingSecondArg(fn) {
                return +/thing\([^,]*,([^,]*)/.exec(fn)[1].trim();
            };
            
            function sum(arr) {
                for (var i=0, result=0; i<arr.length; i++) {
                    result += arr[i];
                }
                return result;
            }
            
            console.log(sum(commandQueue.map(getThingSecondArg)));

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多