正则表达式或函数,用于提取传递给函数的所有参数

a regex or function to extract all the parameters passed to a function

本文关键字:函数 参数 用于 提取 正则表达式      更新时间:2024-04-10

我正在寻找传递给函数的参数

假设我已经有hello作为函数,并且我有一个字符串作为下面的

hello(1,'434','hello,word',"h,g",{a:'b,u', l : { "sk" : "list", bk : 'u,93' }, c : 9},true)

然后在正则表达式或函数上,我应该能够找到以下6个字符串

'1'
'"434"'
'"hello,world"'
'"h,g"'
'{"a":"b,u","l":{"sk":"list","bk": "u,93"},"c":9}'
'true'

根据您的问题,您可以这样做:

x =Hello(1,'434','hello,word',"h,g",{a:'b,u', l : { "sk" : "list", bk : 'u,93' }, c : 9},true);
function Hello() {
    for (i = 0; i <arguments.length; i++) {
        console.log(arguments[i]) 
    }
}

您可以借助argument对象,它是一个类似Array的对象,与传递给函数的参数相对应。

如果这是一个字符串,那么您可能必须首先转义双引号才能得到类似的结果

var x = "hello(1,'434','hello,word','"h,g'",{a:'b,u', l : { '"sk'" : '"list'", bk : 'u,93' }, c : 9},true)";

然后你可以像一样调用它

Function(x)();

hello函数中,您应该迭代参数对象的属性,如

function hello(){
Array.prototype.forEach.call(arguments, prop => console.log(prop));
}

这是我的解决方法。它可能容易出错,但应该比eval解决方案更快。

var extractParameters = function(str){
  var ar = [];
    if(typeof str === 'string' && str.length){
        var chars = str.split(','), cl = chars.length;
        var pushInto = function(n){
            try {
                ar.push(JSON.parse(chars[n]));
            } catch(er){
                ar.push(undefined);
            }
        };
        for(var di, si, eg, fg, n = 0; n < cl; n++){
            eg = chars[n].charAt(0);
            fg = chars[n].charAt(chars[n].length - 1);
            if(eg === fg && (eg === '"' || eg === "'")){
                chars[n] = "'"" + chars[n].substring(1, chars[n].length - 1) + "'"";
            }
            di = chars[n].indexOf('"');
            si = chars[n].indexOf("'");
            if(((si === -1) && (di === -1)) || (eg === fg && (eg === '"' || eg === "'")) ||
                 (chars[n].charAt(0) === "{" && chars[n].charAt(chars[n].length-1) === "}" && (chars[n].match(/'{/g).length === chars[n].match(/'}/g).length))){
                pushInto(n);
            } else if(n < (cl-1)) {
                chars[n] = chars[n] + ','+ chars[n+1];
                chars.splice(n+1,1);
                n--;
                cl--;
                continue;
            }
        }
    }
    return ar;
};

小提琴:https://jsfiddle.net/jv0328tp/16/