'What does Array.prototype.join.call do in the background for a string?
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.
Solution 1:[1]
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:
- Let O be ToObject(this value).
- ReturnIfAbrupt(O).
- Let len be ToLength(Get(O,
"length")). - ReturnIfAbrupt(len).
- If separator is undefined, let separator be the single-element String
",". - Let sep be ToString(separator).
- ReturnIfAbrupt(sep).
- If len is zero, return the empty String.
- Let element0 be Get(O,
"0"). - If element0 is undefined or null, let R be the empty String; otherwise, let R be ToString(element0).
- ReturnIfAbrupt(R).
- Let k be
1. - Repeat, while k < len
- Let S be the String value produced by concatenating R and sep.
- Let element be Get(O, ToString(k)).
- If element is undefined or null, let next be the empty String; otherwise, let next be ToString(element).
- ReturnIfAbrupt(next).
- Let R be a String value produced by concatenating S and next.
- Increase k by 1.
- Return R.
Solution 2:[2]
String is array-like object. An array-like object provides indexed access to elements and the property length. You can read more here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
| Solution 2 | Ruslan Abelharisov |
