오늘 코플릿 문제를 풀다가 요상한 연산자를 발견하였다.
!!
^=

바로 알아보도록 하자.
Not Not 연산자 (!!)
Not연산자는 흔히 사용하는데 도대체 Not Not은 뭐지?
스택오버플로우에 따르면 Not Not 연산자는 아래와 같다.
Converts Object to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.
Not Not 연산자는 객체를 불리안 값으로 전환할 때 사용한다고 한다.
즉 Falsey한 null이나 0 등에 not not을 붙이면 False가 반환되는 것이다!
!oObject // inverted boolean
!!oObject // non inverted boolean so true boolean representation
XOR 연산자 (^=)
XOR 연산자는 이해하기 조금 난해하다.
XOR 연산자는 과거에 두 변수의 값을 메모리 스택 낭비를 최소화 하면서 교환하기 위해 사용되곤 했는데 최근에는
사용하지 않는 추세라고 한다.
이진법에서 XOR은 두 값이 0과 1이면 합쳐서 1을, 0과 0이면 0을, 1과 1이면 0을 반환하는 논리를 가지고 있다.
이러한 논리를 이용해서 아래와 같이 코드를 짜면 두 변수의 값을 tmp 변수 없이 교환 가능하다.
x = x xor y
y = x xor y
x = x xor y
자세한 논리는 아래 위키피디아에 잘 설명되어 있다.
https://en.wikipedia.org/wiki/XOR_swap_algorithm
XOR swap algorithm - Wikipedia
From Wikipedia, the free encyclopedia Jump to navigation Jump to search Using the XOR swap algorithm to exchange nibbles between variables without the use of temporary storage In computer programming, the exclusive or swap (sometimes shortened to XOR swap)
en.wikipedia.org
'Javascript' 카테고리의 다른 글
JS JSON (0) | 2021.11.16 |
---|---|
JS 약식 분기문에 의한 값 할당 방법 (0) | 2021.11.16 |
JS Linked-list & Hash table (0) | 2021.11.11 |
JS 매개변수 기본 값 설정하기 (0) | 2021.11.10 |
JS Tail recursion (0) | 2021.11.10 |