개발일지

개발일지 27일차

index.ys 2023. 4. 13. 01:10

Set

  • 동일한 값을 중복하여 포함할수 없다
  • 요소 순서에 의미가 없다
  • 인덱스로 요소에 접근할 수 없다.

객체선언

- 배열 arr을 객체set으로 만들면 배열안에 중복된 값들은 제거되고 객체로 변환된다.

//배열선언
let arr = [1,1,1,2,2,3,4,4,5,5,6]
//선언한 배열을 Set객체로 변환, 이때 중복된 객체는 모두삭제됨 객체로 생성된 값은 key값
const set = new Set(...arr);

요소 개수 확인

- size속성을 사용해 객체의 길이 파악

//size속성을 사용해 객체 set의 길이를 알수 있다 (length와 비슷)
console.log(set.size) //6

 

객체를 배열로 변환

- 전개연산자 ...를 사용해 객체 set을 배열안에 분해해서 넣을 수 있다.

console.log(set); // {1, 2, 3, 4, 5, 6}
//전개 연산자를 사용해 객체 set을 배열로 변환함.
console.log([...set]);  // [1, 2, 3, 4, 5, 6]

요소추가

- add() 메서드를 사용해 객체에 값을 추가 할 수있다.

- 이때 객체에 입력된값이 중복이면 객체에 추가 되지 않는다.

const set = new Set();

set
  .add(1)
  .add(2)
  .add(2)
  .add(2)
  .add(3)
  .add(4)
  .add(5)
  .add(5)
  .add(5)
  .add(6)
console.log(set); // [1,2,3,4,5,6]

요소 존재 여부확인

- has() 메서드를 사용해 객체안에 특정요소가 있는지 없는지에 따라 true or false를 반환한다.

const set = new Set([1, 2, 3, 4 , 5 , 6 , 7]);
console.log(set) //{ 1 , 2 , 3 , 4 , 5 , 6 , 7 }

console.log(set.has(2)); // true
console.log(set.has(9)); // false
console.log(set.has(1)); // true
console.log(set.has(6)); // true

요소삭제

- delete() 메서드를 사용하여 객체안의 지정된 값을 삭제할 수 있다.

const set = new Set([1, 2, 3, 4 , 5 , 6 , 7]);
console.log(set) //{ 1 , 2 , 3 , 4 , 5 , 6 , 7 }

// 요소5를 삭제
set.delete(5)

// 요소4를 삭제
set.delete(4)

console.log(set) //{1, 2, 3, 6, 7}

for in

- 객체를 하나씩 순회하며 특정 작업을 수행하는 반복문

let obj ={
	name: "짱구",
    age: 5,
    hasJob: true,
    job : "student"
}


for(let i in obj ){
	console.log(i)
    //name
	//age
	//hasJob
	//job
}

padStar()

- String 메서드로 특정 문자를 원하는 길이만큼 채울 수 있는 문자열 메서드이다

String.padStar("원하는 문자열의 길이" , "문자열의 앞부터 채우고싶은 특정문자" )

const str = 'Hello';

console.log(str.padStart(7, '0')); // "00Hello"



const str2 = 'hi';

console.log(str2.padStart(12, 't')) ; //tttttttttthi

console.log(str2.padEnd(4, 'y')) ;  //hiyy