JsにおけるES 6のSetの基本的な使い方

28824 ワード

参考:阮一峰ES 6入門のセット
ES 6は、新しいデータ構造Setを提供する.配列に似ていますが、メンバーの値は全部唯一で、重複した値はありません.
const s = new Set();

[2,3,5,4,5,2,2].forEach(x => s.add(x));
// Set          

for(let i of s) {
  console.log(i);
}


// ##    
//                
const set = new Set([1,2,3,4,4,]);

// ...                 
console.log([...set]);

//   
const items = new Set([1,2,3,4,5,5,5,5,]);
console.log(items.size);


//          iterable             
const set2 = new Set(document.querySelectorAll('div'));
console.log(set.size);

//    
const set2 = new Set();
document
    .querySelectorAll('div')
    .forEach(div => set.add(div));
console.log(set.size);

// set NaN    ,        ===
let set3 = new Set();
let a = NaN;
let b = NaN;
set3.add(a);
set3.add(b);
console.log(set3)

//           
let set4 = new Set();
set4.add({});  // 1
console.log(set4.size);

set4.add({});  // 2
console.log(set4.size);
const s = new Set();

s.add(1).add(2).add(2);

console.log(s.size);

console.log(s.has(1));
console.log(s.has(2));
console.log(s.has(3));

s.delete(2);
console.log(s.has(2));

// set   
const items = new Set([1,2,3,4,5]);
const array = Array.from(items);
console.log(array);

//         
function dedupe(array) {
  return console.log(Array.from(new Set(array)));
}

dedupe([1,1,2,3]);
let set = new Set(['red', 'green', 'blue']);

//     
for(let item of set.keys()) {
  console.log(item);
}

//     
for(let item of set.values()) {
  console.log(item);
}
// set   =  

//      
for(let item of set.entries()){
  console.log(item);
}

//       for of  Set
// for in   for of    :in      ,of    
for (let x of set) {
  console.log(x);
}

// set  forEach()  
set.forEach((value, key) => console.log(key + ' : ' + value));
//   forEach            。

//     map   filter          Set
let s = new Set([1,2,3]);

// map           
s = new Set([...s].map(x => x * 2));
console.log(s);

// filter         
s = new Set([...s].filter(x => (x % 3) ==0));
console.log(s);

//     、  、  
let a = new Set([1,2,3]);
let b = new Set([4,3,2]);

let union = new Set([...a, ...b]);
console.log(union);

let intersect = new Set([...a].filter(x => b.has(x)));
console.log(intersect);

let difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference);

//       ,       Set         

// 1.   Set           ,        Set  
let set1 = new Set([1,2,3]);
set1 = new Set([...set1].map(val => val *2));
console.log(set1);

// 2.  Array.from
let set2 = new Set([1,2,3]);
set2 = new Set(Array.from(set2, val => val * 2));
console.log(set2);