正则表达式或函数,用于提取传递给函数的所有参数
a regex or function to extract all the parameters passed to a function
我正在寻找传递给函数的参数
假设我已经有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/
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 为什么不'我们在javascript中使用函数参数的数据类型
- 使用闭包共享构造函数参数
- 函数参数的值错误
- 当一个重要的构造函数参数丢失时应该发生什么
- 阻止ReSharper将JavaScript函数参数放到新行中
- 根据函数参数将CSS值存储在var中,然后对其进行操作
- 使构造函数参数具有ES6类方法的特权
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- Windows.Networking.EndpointPair构造函数参数
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 大括号中的Javascript函数参数
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 将JSON字符串转换为函数参数
- eval()读取函数参数有多糟糕
- Javascript不能在一个命令中使用函数参数
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- ES6类构造函数参数
- 是否可以在javascript函数参数列表中调用多个函数