const set = new Set("123");
console.log(set);
Output is "Set { '1', '2', '3' }"
CodePudding user response:
The Set
constructor takes an iterable and takes every value of it.
Strings have an @@iterator
property by default which makes them iterable:
const foo = "xyz";
console.log(...foo);
const [a, b, c] = foo;
console.log(a, b, c);
for (const char of foo)
console.log(char);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Therefore, this is exactly what happens when you pass a string to a Set
constructor - it draws every value just as it would with any other iterable:
const foo = "xyz";
const bar = [1, 2, 3]
console.log("set of string:", new Set(foo));
console.log("set of array :", new Set(bar));
<h1>Check the browser console</h1>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Because strings are iterable, and when you give the Set
constructor an iterable object,¹ it loops through the values provided by the object's iterator and adds them to the set. In the case of strings, the string iterator iterates the strings code points — in your example, "1"
, "2"
, and "3"
. (For more about "code points" vs. "code units" and what a string is, read my blog post.)
If you want to add a string to a set, you have to do add separately or wrap it in another iterable (like an array):
// Add separately:
let set = new Set();
set.add("123");
console.log(set.size); // 1
console.log([...set]); // ["123"]
// Or wrap:
set = new Set(["123"]);
console.log(set.size); // 1
console.log([...set]); // ["123"]
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
¹ (or a primitive such as a string that coerces to an iterable object)