자바스크립트 스터디 - set 과 map (7장)

BackEnd_Ash.log·2021년 3월 14일
0

set

ES6 에서는 중복은 없고 순서는 있는 값의 리스트인 set 타입을 추가하였다.

add

let set = new Set();
set.add(5);
set.add("5");

console.log(set.size); //2 
console.log(set); // Set(2) { 5, '5' }

set 안에 객체도 넣을 수가 있다.

let set = new Set(),
key1 = {},
key2 = {};

set.add(key1);
set.add(key2);

console.log(set); // Set(2) { {}, {} }
console.log(set.size); // 2

중복 제거

let set = new Set([1,2,3,4,5,5,5,5]);

console.log(set); // Set(5) { 1, 2, 3, 4, 5 }
console.log(set.size); // 5

hash

let set = new Set();
set.add(5);
set.add("5");

console.log(set.has(5)); // true
console.log(set.has(6)); // false

요소 제거하기

let set = new Set();
set.add(5);
set.add("5");

console.log(set.has(5)); // true

set.delete(5);

console.log(set.has(5)) // false
console.log(set); // Set(1) { '5' }

set.clear();

console.log(set.has("5")); // false
console.log(set); // Set(0) {}

foreach

const arr = [2,4,2,3,6,7]
const new_arr = []
arr.forEach((n)=>{if(n%2===0) new_arr.push(n)});
console.log(new_arr); //[ 2, 4, 2, 6 ]
const arr = [2,4,2,3,6,7]
const new_arr = []
arr.forEach((n)=>{new_arr.push(n*2)});
console.log(new_arr); //[ 4, 8, 4, 6, 12, 14 ]

map()

인자값 : currentValue , index , array
요소를 일괄적으로 변경

const arr = ["test" , "really test" , "good test"];
const arr2 = arr.map((v)=>v.length);

console.log(arr2); // [4 ,11 ,9]

filter()

요소를 걸러내어 배열로 true/false 반환 , 없으면 빈배열

const arr = [4 , 2 ,3 ,5 ,67, 1,9 ,5 ,10];
const arr2 = arr.filter((v)=>(v%3===0));
console.log(arr2); // [ 3, 9 ]

set 을 배열로 변환하기

Map

  • 순서가 있는 키와 값 쌍의 리스트이다.
const map = new Map();
map.set("title","Understanding ECMAScript 6");
map.set("year",2016);

console.log(map); // Map(2) { 'title' => 'Understanding ECMAScript 6', 'year' => 2016 }
console.log(map.get("title")); // Understanding ECMAScript 6
console.log(map.get("year")); // 2016

map을 만들 때 객체 프로퍼티를 키로 사용하는 것이 불가능 했지만 ,
Map 에서는 객체를 키로 사용할 수도 있다.

객체를 키

Map 의 키로 객체 key1 과 key2 를 사용한다.

이 키들은 다른 형태로 변환 되지 않기 때문에 , 각 객체는 유일한 것으로 간주된다.

map 의 메서드

  • has(key) : 주어진 키가 map 에 존재하는지 확인
  • delete(key) : 키와 키에 연관된 값을 Map으로부터 제거
  • clear() : 모든 키와 값을 Map 으로부터 제거

map 의 초기화

map 의 forEach 메서드

map 의 forEach() 메서드는 세 개의 인자를 가진 콜백 함수를 받는다는 점에서 Set 이나 배열과 유사하다.

  • Map 의 다음 위치 값
  • 값에 대한 키
  • 값을 읽어들이고 있는 Map

profile
꾸준함이란 ... ?

0개의 댓글