var a = "foo";
var c = Array.prototype.join.call( a, "-" ); // 'f-o-o'
How does the second line of code work? I don't see any conversion of the string to an array and then converting back again, is this happening in the background? I've encountered this kind of code and it's very weird, an array method accepting a string.
See the specification for Array.prototype.join (below). It doesn't require that the this it's operating on be an array, merely that it have a length and properties with names like 0, 1, and so on. Strings do, and so join can work on a string.
From the spec:
NOTE 2 The
joinfunction is intentionally generic; it does not require that itsthisvalue be anArrayobject. Therefore, it can be transferred to other kinds of objects for use as a method.
Here's the full algorithm from the spec:
"length")).","."0").1.A string is an Array like object, because it has the property length and you can access its elements (chars) using [] as of that you can apply most of the array manipulation operations on it.
The Function.prototype.call() calls the function given function with using the first parameter as this and the flowing one as normal parameters.
As of that Array.prototype.join.call(a, "-") will call the function join on the object a in you case the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With