Javascript 为什么字符串concat apply不能按预期工作?

Javascript 为什么字符串concat apply不能按预期工作?,javascript,concat,Javascript,Concat,我对字符串调用concat(),如下所示: > "1".concat("2","3") < "123" 使用prototypeString.prototype并使用函数.join()连接数组值 console.log(String.prototype.concat(“1”,“2”,“3”].join(“”))的第一个参数是上下文,它需要是字符串。你会用 const arr = ["2","3"]; console.log("1".concat(...arr)); console.

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

> "1".concat("2","3")
< "123"

使用prototype
String.prototype
并使用函数
.join()
连接数组值

console.log(String.prototype.concat(“1”,“2”,“3”].join(“”))
的第一个参数是上下文,它需要是字符串。你会用

const arr = ["2","3"];
console.log("1".concat(...arr));
console.log(String.prototype.concat.apply("1", arr));
console.log("".concat.apply("1", arr));
在您的特殊情况下,我建议使用:

或者在ES5中

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

如果要根据字符串或数组原型使用concat,可以使用

var stringOrArray=“1”
log(Object.getPrototypeOf(stringOrArray.concat.apply(stringOrArray,[“2”,“3”]))
Stringorary=[“1”,“5”]

console.log(Object.getPrototypeOf(stringOrArray.concat.apply(stringOrArray,[“2”,“3”]))
在JavaScript中使用本机函数时,我建议阅读第一个

通过调用
“1”.concat
可以获得字符串对象的原始函数,从而丢失上下文。如果要使用
apply
调用函数,第一个参数是函数用作其
this
对象或上下文的对象

因此
“1”.concat.apply([“2”,“3”])
在语义上等同于
(“+[“2”,“3”]).concat()

我想你想做的是:

var unboundConcat = String.prototype.concat;
return unboundConcat.apply("1", ["2", "3"]);

apply
的第一个参数是上下文,或
this

在ES6中:

  • aORs=数组或字符串
  • concatWith=将数组或字符串连接到的内容

    let concat=(aORs)=>(concatWith)=>aORs.concat(concatWith)

let concat=(aORs)=>(concatWith)=>aORs.concat(concatWith);
console.log(
concat([“a”,“b”])(1)
); 
//[“a”,“b”,1]
console.log(
concat(“1”)(“2”)
);

//“12”
它为您提供了一个新的数组常量
newArray=“1”。concat(“2”,“3”)
@michael只是想知道这是否发生在特定的浏览器中,或者您是否测试了多个
[“1”,“2”,“3”]。join(“”)
?@S.Imp我在Chrome和Firefox@zfrisch当Stringorary是一个非常好的答案时,这将给出错误的结果。我习惯于将“null”或“this”作为第一个要应用的参数,当它开始抛出错误时,我感到困惑,所以我删除了它,发现它似乎不介意(除了返回错误的结果!)现在对我来说很明显,第一个参数正在转换为字符串,并且没有任何连接。像uglify这样的缩小工具将在省略号
…arr
上呕吐。这可能是一个考虑因素,也可能不是。扩展方法可能对大型阵列有影响?@S.Imp您应该使用与ES6兼容的现代缩小工具。我想更重要的考虑因素是您是否需要支持ES6之前的浏览器:-)@S.Imp我不能推荐任何浏览器,因为我个人从未使用过,但是
function concat(x, ...args) {
    return x.concat(...args);
}
function concat(x) {
    var args = Array.prototype.slice.call(arguments, 1);
    return x.concat.apply(x, args);
//                        ^
}
var unboundConcat = String.prototype.concat;
return unboundConcat.apply("1", ["2", "3"]);