使用参数数组调用String.prototype.split

时间:2017-02-01 18:27:47

标签: javascript arrays string split

我有一些逻辑需要在某些时候运行本机JavaScript函数并将“动态”参数传递给这些函数。例如,我需要在定义为split

的参数数组上调用["i want to split this", " " ]函数

我到目前为止所做的是以下内容:

String.prototype.split.call("i want to split this", " ")工作正常,但由于我的参数是数组,所以我需要使用apply。但是:

String.prototype.split.apply(null, ["i want to split this", " " ])

无效,我将获得Uncaught TypeError: String.prototype.split called on null or undefined

有效的方法是使用带有call语法的spread ..以便:

String.prototype.split.call(...["i want to split this", " " ])

但问题是我的Node.js版本还不支持spread语法。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您正在寻找

String.prototype.split.apply("i want to split this", [" "])

相当于

String.prototype.split.call("i want to split this", " ")

如果你有一个数组来代替上下文和参数,你可以做

var arr = ["i want to split this", " "];
String.prototype.split.apply(arr[0], arr.slice(1))

或(如果你不关心变异):

String.prototype.split.apply(arr.shift(), arr)