我目前需要将一组函数参数定义为逗号分隔的字符串,并在稍后传入。
我希望我的代码按如下方式运行。
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/