为什么string concat应用不按预期工作?

Mic*_*ael 3 javascript concat

我调用concat()一个字符串,如下所示:

> "1".concat("2","3")
< "123"
Run Code Online (Sandbox Code Playgroud)

现在我想这样做,我有一个字符串数组连接togther.但它并没有达到我的预期:

> "1".concat.apply(["2","3"])
< "2,3"
Run Code Online (Sandbox Code Playgroud)

不仅缺少第一个元素,而且在传递的两个元素之间插入了一个逗号,就像它将apply中的参数转换为字符串然后返回它一样.

我怎么用申请?我无法使用,String.prototype.concat.apply因为第一个参数实际上是一个可以是字符串或数组的变量.我宁愿不做一些可怕的黑客,我必须检测类型,然后为参数可能的每种可能的类型单独声明.

为了清楚起见,我正在尝试实现一个concat()适用于任何有意义的第一个参数类型的函数(例如字符串或数组).到目前为止它看起来像这样,但是不起作用:

function concat(x) {
    var args = Array.prototype.slice.call(arguments,1)
    return x.concat.apply(args)
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

第一个参数apply是上下文,它需要是字符串.你用的

const arr = ["2","3"];
console.log("1".concat(...arr));
console.log(String.prototype.concat.apply("1", arr));
console.log("".concat.apply("1", arr));
Run Code Online (Sandbox Code Playgroud)

在您的特定情况下,我建议使用rest/spread语法:

function concat(x, ...args) {
    return x.concat(...args);
}
Run Code Online (Sandbox Code Playgroud)

或者在ES5中

function concat(x) {
    var args = Array.prototype.slice.call(arguments, 1);
    return x.concat.apply(x, args);
//                        ^
}
Run Code Online (Sandbox Code Playgroud)