Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
Why is Set object split string?
const set = new Set("123");

console.log(set);

Output is "Set { '1', '2', '3' }"

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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"]


¹ (or a primitive such as a string that coerces to an iterable object)

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda