将字符串传递给Function.prototype.apply()JavaScript

将字符串传递给Function.prototype.apply()JavaScript,javascript,regex,Javascript,Regex,我目前需要将一组函数参数定义为逗号分隔的字符串,并在以后传入 我希望我的代码能起到如下作用 function bar() { console.log("My name is " + arguments[0].name + " and my species is " arguments[0].species); console.log("String 1: " + arguments[1]); console.log("String 2: " + arguments[2])

我目前需要将一组函数参数定义为逗号分隔的字符串,并在以后传入

我希望我的代码能起到如下作用

function bar() {
    console.log("My name is " + arguments[0].name + " and my species is " arguments[0].species);
    console.log("String 1: " + arguments[1]);
    console.log("String 2: " + arguments[2]);
}

function foo() {
    var args = "{name: 'Dean Brunt', species: 'Human'}, 'A string', 'Some other input string, oh yes'";
    bar.apply(null, args);
}
我希望这样可以生成控制台的输出:

My name is Dean Brunt and my species is Human
String 1: A string
String 2: Some other input string, oh yes
但是,这不能作为
Function.prototype.apply()
的第二个参数使用数组。虽然我曾尝试将args字符串转换为数组,但由于这会导致非平凡的正则表达式拆分,我一直在努力解决这个问题,我的尝试也没有成功

有谁能帮我定义一个合适的正则表达式对象,我可以使用它进行拆分,或者建议一个可以产生相同结果的替代方法


非常感谢。

它不漂亮,但您可以使用
eval

功能条(){
log(“我的名字是“+参数[0].name+”,我的物种是“+参数[0].species”);
log(“字符串1:+参数[1]);
log(“字符串2:+参数[2]);
}
函数foo(){
var args=“{name:'Dean Brunt',species:'Human'},'一个字符串','其他一些输入字符串,哦是';
bar.apply(null,eval('['+args+']');
}
foo()您可以使用eval()。
编写正则表达式将相当乏味

function stringToArgs(str){
   return eval(`(function(){return arguments;})(${str})`);
}

function bar(arguments) {
    console.log("My name is " + arguments[0].name + " and my species is " +arguments[0].species);
    console.log("String 1: " + arguments[1]);
    console.log("String 2: " + arguments[2]);
}

function foo() {
    var args = "{name: 'Dean Brunt', species: 'Human'}, 'A string', 'Some other input string, oh yes'";
    bar(stringToArgs(args));
}

foo();

这不是傻瓜式的,但这是一个开始

您应该首先将数据格式化为JSON格式,然后对其进行解析。这是最简单的方法

函数printInfo(){
log(“我的名字是“+参数[0].name+”,我的物种是“+参数[0].species”);
log(“字符串1:+参数[1]);
log(“字符串2:+参数[2]);
}
函数parseInfo(){
var jsonStr='['+repairJson(参数[0])+'];
var jsonObj=JSON.parse(jsonStr);
printInfo.apply(null,jsonObj);
}
//添加和修复报价。
函数(str){
返回str.replace(/[']/g',“')。replace(/(\b\w+\b):/g',“$1:”);
}

parseInfo({name:'Dean Brunt',species:'Human'},'A string','Some other input string,oh yes')
什么是var args?它会抛出一个语法错误,在双引号中加上双引号。一旦这是一个有效的对象/字符串,你可以用括号将其包装成一个1元素数组,一切都应该很好。@James这是我的一个输入错误。args应该是一个字符串,它表示一组逗号分隔的值,这些值将作为也就是说,由于这个原因,我不知道如何包装它作为一个1元素数组将工作,然后肯定地<代码>应用< /C> >将奇异元素视为唯一的函数参数,而不是我想要的3个分离的参数。ARG从何而来?为什么它是一个字符串?@从数据属性中拉取MelpOMeN-ARGS。在HTML元素上。我的规范规定该属性包含逗号分隔的值,这些值将传递给预定义函数。非常好,这可以满足我的需要,即使不美观。我完全忘记了eval的存在。非常感谢。您可以使用JSON.parse而不是eval。