-1

I want to get test2 as String but I got only "1" instead of "1, 2, 3".

let test = [1, 2, 3];
console.log(String(test));

let test2 = new Set([1, 2, 3]);
console.log(String(...test2));
Ivar
  • 6,138
  • 12
  • 49
  • 61
user310291
  • 36,946
  • 82
  • 271
  • 487
  • 1
    Why do you expect the [`String` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String) to understand multiple arguments (`String(1, 2, 3)`)? – Andreas Oct 05 '21 at 10:17
  • 1
    [What is the meaning of "...args" (three dots) in a function definition?](https://stackoverflow.com/questions/42184674/what-is-the-meaning-of-args-three-dots-in-a-function-definition) – Andreas Oct 05 '21 at 10:19
  • @Andreas why not since she understands array – user310291 Oct 05 '21 at 10:23
  • An array is one element. `String()` can handle one element (as long as it can be converted into a string). `...array` is not one element... – Andreas Oct 05 '21 at 10:26

2 Answers2

1

String() converts an array to a string.

You were not converting Set into an array correctly, you just needed square brackets with the spread operator.

let test2 = new Set([1, 2, 3, 3]);
console.log(String([...test2]));
ahsan
  • 1,409
  • 8
  • 11
1

String(...test2) spreads out the elements from the set into discrete arguments to String. With your example set, it's the same as doing String(1, 2, 3). The String function doesn't do anything with any arguments you pass it other than the first one, so String(1, 2, 3) gives you the same result as String(1): It converts the argument to string, returning "1".

If you want to get, say, "1, 2, 3", you could spread the contents of the set into an array and use join:

let test2 = new Set([1, 2, 3]);
console.log(
    [...test2].join(", ")
);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875