“iterate set javaScript” Código de respuesta

JS iterate set

const mySet = new Set( [ { a: 1 }, { b: 2 } ] );

// A) Using forEach()
mySet.forEach( item => console.log( item ) );

// B) Using for ... of
for (let item of mySet) {
  console.log(item);
}
// Output:
// { a: 1 }
// { b: 2 }
KostasX

JS iterating set

// iterate over items in set
// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet1) console.log(item)

// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet1.keys()) console.log(item)

// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
for (let item of mySet1.values()) console.log(item)

// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
// (key and value are the same here)
for (let [key, value] of mySet1.entries()) console.log(key)

// convert Set object to an Array object, with Array.from
const myArr = Array.from(mySet1) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}]

// the following will also work if run in an HTML document
mySet1.add(document.body)
mySet1.has(document.querySelector('body')) // true

// converting between Set and Array
const mySet2 = new Set([1, 2, 3, 4])
mySet2.size                    // 4
[...mySet2]                    // [1, 2, 3, 4]

// intersect can be simulated via
const intersection = new Set([...mySet1].filter(x => mySet2.has(x)))

// difference can be simulated via
const difference = new Set([...mySet1].filter(x => !mySet2.has(x)))

// Iterate set entries with forEach()
mySet2.forEach(function(value) {
  console.log(value)
})

// 1
// 2
// 3
// 4
Puzzled Puffin

iterate set javaScript

function logSetElements(value1, value2, set) {
  console.log(`s[${value1}] = ${value2}`);
}

new Set(['foo', 'bar', undefined]).forEach(logSetElements);

// expected output: "s[foo] = foo"
// expected output: "s[bar] = bar"
// expected output: "s[undefined] = undefined"
Homemadesteam58

Respuestas similares a “iterate set javaScript”

Preguntas similares a “iterate set javaScript”

Más respuestas relacionadas con “iterate set javaScript” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código