我在字符串上调用 concat()
,如下所示:
> "1".concat("2","3")
< "123"
现在我想在我有一个字符串数组要连接在一起的情况下执行此操作。但它没有达到我的预期:
> "1".concat.apply(["2","3"])
< "2,3"
不仅缺少第一个元素,而且在传递的两个元素之间插入了一个逗号,就像它正在将 apply 中的参数转换为字符串然后返回它一样。
我如何使用申请?我不能使用 String.prototype.concat.apply
因为第一个参数实际上是一个变量,可以是字符串或数组。我宁愿不做一些可怕的黑客攻击,我必须检测类型,然后为每个可能的参数类型都有一个单独的语句。
明确地说,我正在尝试实现一个函数 concat()
,它适用于任何有意义的第一个参数类型(例如字符串或数组)。到目前为止它看起来像这样,但不起作用:
function concat(x) {
var args = Array.prototype.slice.call(arguments,1)
return x.concat.apply(args)
}
最佳答案
apply
的第一个参数是上下文,需要是字符串。你会用
const arr = ["2","3"];
console.log("1".concat(...arr));
console.log(String.prototype.concat.apply("1", arr));
console.log("".concat.apply("1", arr));
在您的特定情况下,我建议使用 rest/spread syntax :
function concat(x, ...args) {
return x.concat(...args);
}
或者在 ES5 中
function concat(x) {
var args = Array.prototype.slice.call(arguments, 1);
return x.concat.apply(x, args);
// ^
}
关于javascript - 为什么 string concat apply 不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139213/