如何在不调用它的情况下查询javascript函数的参数

lea*_*vst 4 javascript function introspection

给定一个命令队列,如下所示..

var commandQueue = [
        function() {thing(100, 0, shiftFunc)},
        function() {thing(100, 233, shiftFunc)},
        function() {thing(100, 422, shiftFunc)}
];
Run Code Online (Sandbox Code Playgroud)

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

Nin*_*olz 6

您可以使用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));
Run Code Online (Sandbox Code Playgroud)