JavaScript Set()이란?

김진원·2022년 10월 30일

JS

목록 보기
8/11
post-thumbnail

Set() 객체의 특성과 생성

Set 메서드는 생성자 함수를 통해 객체를 생성할 수 있다. 인수에는 자료형과 관계없이 원시타입의 데이터는 모두 전달할 수 있다.

만약 인수에 값이 빈 값일 경우에는 빈 객체가 생성된다.

Set()메서드는 고유의 값만 저장이 되는 특성을 가지므로, 중복값은 저장되지 않는 특성을 갖고 있다.

let set = new Set(); // Set(0) {} 빈 Set객체 생성

let set = new Set('a'); // Set(1) { 'a' } 

let set = new Set(key : )

Set 객체 add 요소 추가

add를 통하여 요소를 추가할 수 있다.

let set = new Set();

set.add('a')
set.add(1)
set.add([1,2,3,4])
set.add([3,4,5,6]) 

// 최종적으로 Set(4) { 'a', 1, [ 1, 2, 3, 4 ], [ 3, 4, 5, 6 ] }

Set.size length 파악

size를 통해 Set 내부 항목의 개수를 알 수 있다.

let set = new Set();

set.add('a')
set.add(1)
set.add([1,2,3,4])
set.add([3,4,5,6]) 

// Set(4) { 'a', 1, [ 1, 2, 3, 4 ], [ 3, 4, 5, 6 ] }

console.log(set.size) // 4

has(data) 데이터 포함 여부

has함수를 통해 Set 객체내의 해당 데이터가 포함 되어 있는지 true/false로 반환한다.

let set = new Set();

set.add('a')
set.add(1)


// Set(2) { 'a', 1 }

console.log(set.has('a')) // true
console.log(set.has(2)) // false

delete(data) / clear 데이터 제거

delete를 통해 객체 안의 데이터를 제거한다. delete이후엔 size와 has 등의 결과값의 반영된다.

clear는 Set객체의 전체를 깨긋하게 삭제한다.

let set = new Set();

set.add('a')
set.add(1)


// Set(2) { 'a', 1 }

set.delete('a') 

console.log(set) // Set(1) { 1 }

set.has('a') // false
set.size // 1

set.clear() // Set(0) {}

반복문을 통한 값 접근

let set = new Set();

set.add('a')
set.add(1)
set.add([2,3,4])
set.add([5,6,7])

for (let item of set) console.log(item);
// 
a
1
[ 2, 3, 4 ]
[ 5, 6, 7 ]

for (let item of set) console.log(typeof item);
// 밑에 결과처럼 각각의 자료형 그대로 반환
string
number
object
object


// forEach로 set 항목 반복
set.forEach(function(value) {
  console.log(value); // for문과 같은값 반환
});

Set 객체 배열로 변환

전개연산자, Array.from(), 반복문등을 통해 배열로 변환할수 있다.

et set = new Set();


set.add('a')
set.add(1)
set.add([2,3,4])
set.add([5,6,7])

// 전개연산자

let spread = [...set] 

// Array.from()

const arr = Array.from(set); 

// forEach 반복문

let empty = [] // 빈배열 생성

set.forEach((element) => {
  empty.push(element);
})

// 위의 세가지 방법다 [ 'a', 1, [ 2, 3, 4 ], [ 5, 6, 7 ] ] 동일값을 반환한다.
profile
사용자의 관점에 대해 욕심이 많은 개발자

0개의 댓글