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

问题描述 投票:3回答:5

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

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

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

> "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)
}
javascript concat
5个回答
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));

在您的特定情况下,我建议使用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);
//                        ^
}

1
投票

在JavaScript中使用本机函数时,我建议首先阅读MDN

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

所以"1".concat.apply(["2", "3"])在语义上等同于(""+["2", "3"]).concat()

我想你想要做的是以下内容:

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

0
投票

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

console.log(String.prototype.concat("1", ["2","3"].join('')))

0
投票

如果要根据String或Array原型使用concat,可以使用Object.getPrototypeOf()

var stringOrArray = "1"

   
console.log(Object.getPrototypeOf(stringOrArray).concat.apply(stringOrArray, ["2","3"]))

stringOrArray = ["1", "5"]

   
console.log(Object.getPrototypeOf(stringOrArray).concat.apply(stringOrArray, ["2","3"]))

0
投票

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")
);
// "1 2"

ES5

function concat(aORs) {
 return function(concatWith) {
   return aORs.concat(concatWith);
 }
}

function concat(aORs) {
  return function(concatWith) {
    return aORs.concat(concatWith);
  }
}

console.log(
  concat("1")("abc")
);

console.log(
  concat([1, 2, 3])("abc")
);
© www.soinside.com 2019 - 2024. All rights reserved.