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

标签 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 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:

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, eval('[' + args + ']'));
}

foo();

关于javascript - 将字符串传递给 Function.prototype.apply() JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332383/

相关文章:

javascript - 从循环中的文本数组分页 HTML textarea 内容

javascript - 在 Safari 中获取 Google map 链接或网页链接

Javascript正则表达式测试字符串是否在分隔行上只有数字

java - 用于处理字符或行尾的正则表达式匹配器

r - 如何将字符串中的括号提取到新列中

javascript - 如何阻止按钮的后续点击事件?

javascript - 如何获取每个 map 'move'(平移、缩放和输出)上的纬度和经度(来自 map.getCenter())值?

javascript - 如何从 <function scope >'s Closure in Chrome Developer tool' s Watch 面板访问值?

regex - 检查网址是否为有效的 Google 搜索网址

javascript - 用于至少一个字母表 (A-z) 的名称验证的正则表达式