본문 바로가기
Dev/🟨 JavaScript

[JS] JavaScript 문법 노트 ( map, set, || , nullish )

by 아아덕후 2023. 2. 22.
반응형
목차
1. map
2. set 
3. || 논리연산자 
4. nullish 연산자
5. 반복문 중간에 끝내기 ! 

1. map

객체 배열에서 map을 사용하여 동일한 key 값을 가진 value 출력하기.

const ajax = new XMLHttpRequest();                                 // ajax 통신
ajax.open("GET", "https://api.hnpwa.com/v0/news/1.json", false);   // 객체 데이터 받기 위함
ajax.send();

const newFeed = JSON.parse(ajax.response).splice(0, 5);            // 객체 데이터 5개만 가져오기!

//  map : 배열 객체에서 동일한 key 값을 가진 value 뽑아내기
console.log("newFeed 원본",newFeed);
console.log("newFeed map",newFeed.map((ele) => ele.title));


 

2. set

배열에서 중복 값 제거한 배열 출력하기

const testArray = [ 1, 2, 1, 2, 2, 4, 5, 6, 7, 3, 35, 32, 2, 1, 2, 2, 4, 5,];

console.log([...new Set(testArray)]);


3. || 연산자

const test0 = 0 || "" || null || undefined || "마지막 값 출력";
const test1 = 0 || "0";
const test2 = "" || "''값";
const test3 = null || "null 값";
const test4 = undefined || "undefined 값";

console.log("test0:", test0);
console.log("test1:", test1);
console.log("test2:", test2);
console.log("test3:", test3);
console.log("test4:", test4);

|| 연산자는 [ 0, “” (빈 문자열), null , undefined] 을 false로 반환한다.
오른쪽 값을 실행 시킨다.

 

 

 

 


4. nullish coalescing operator ( ?? ) 

const test5 = 0 ?? "0 값";
const test6 = "" ?? "''값";
const test7 = null ?? "null 값";
const test8 = undefined ?? "undefined 값";
const test9 = undefined ?? null ?? undefined;

console.log("test5:", test5);
console.log("test6:", test6);
console.log("test7:", test7);
console.log("test8:", test8);
console.log("test9:", test9);

nullish 병합 연산자(nullish coalescing operator)
null ?? undefined ?? 'abcd'
?? 연산자는 null , undefined 인 경우라면, false로 반환하고 오른쪽 값을 실행 시킨다.

 

 

 

 


5. 반복문 종료 조건

반복문(for loop) 중간에 끝내기 

프로그래밍에서 가장 중요한 시간 리소스를 아끼기 위해서

원하는 결과를 얻어내면 바로 종료하는 것이 중요하다.(시간복잡도) 

따라서 반복문을 사용해야 하는 경우에 원하는 값을 얻어 즉시 종료시키는 것이 조금 더 나은 프로그래밍을 할 수 있다.

// some 
[1, 2, 3, 4, 5].some((x) => {
  if (x == 3) {
    console.log("종료");
    return true;
  } else {
    console.log(x);
  }
  console.log("진행중");
});

============================
// 출력 값
// 1
// 진행중
// 2
// 진행중
// 종료
// true

 

반응형

댓글