Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does string concat apply not work as expected?

I call concat() on a string as shown below:

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

Now I want to do this for the case where I have an array of strings to concat togther. But it doesn't do what I expect:

> "1".concat.apply(["2","3"])
< "2,3"

Not only is the first element missing, but a comma has been inserted between the two elements passed, like it was converting the argument in apply to a string and then returning that instead.

How can I use apply? I can't use String.prototype.concat.apply because the first argument is actually a variable which could be string or array. I would rather not do some awful hack where I have to detect the type and then have a separate statement for each possible type the argument could be.

To be clear, I am trying to implement a function concat() which works for any first argument type which makes sense (e.g. string or array). So far it looks like this, but is not working:

function concat(x) {
    var args = Array.prototype.slice.call(arguments,1)
    return x.concat.apply(args)
}
like image 339
Michael Avatar asked May 24 '26 09:05

Michael


1 Answers

The first argument of apply is the context, which needs to be the string. You'd use

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

In your particular case, I'd recommend to use rest/spread syntax:

function concat(x, ...args) {
    return x.concat(...args);
}

or in ES5

function concat(x) {
    var args = Array.prototype.slice.call(arguments, 1);
    return x.concat.apply(x, args);
//                        ^
}
like image 108
Bergi Avatar answered May 26 '26 21:05

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!