“ITERATE Set JavaScript” Respostas de código

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

conjunto de iteração js

// 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

Respostas semelhantes a “ITERATE Set JavaScript”

Perguntas semelhantes a “ITERATE Set JavaScript”

Mais respostas relacionadas para “ITERATE Set JavaScript” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código