JavaScript #연산자의 종류 및 getType

달다로·2024년 6월 5일
0

JS

목록 보기
13/26
post-thumbnail

📌연산자의 종류


산술 연산자 (arithmetic operator)

console.log(1 + 2) // 3
console.log(5 - 2) // 3
console.log(9 * 3) // 3
console.log(15 / 5) // 3

나머지 연산자

7 / 5 = 1 그리고 나머지 2

console.log(7 % 5) // 2

할당 연산자 (assignment operator)

예시 1번

const a = 2 // 2 라는 것을 a 에 할당 하는 것
let a = 2
a = a + 1
console.log(a)

예시 2번

const a = 2 // 2 라는 것을 a 에 할당 하는 것
let a = 2
a += 1
console.log(a)

비교 연산자 (comparison operator)

1) 일치 연산자 (===)

예시 1번

const a = 1
const b = '1'
console.log(a === b)// 숫자가 달라서 false
console.log(a == b)// 숫자가 같아서 true

예시 2번

function isEqual(x, y) {
	return x === y
}
console.log(isEqual(1, 1))

2) 불일치 연산자 (!==)

const a = 3
const b = 1
console.log(a !== b) // 서로 다른지 확인하는 기호

3) 비교 연산자 (<, >, >= ...)

=< 의 반드시 뒤에 위치해야한다.
예시 1번

const a = 3
const b = 1
console.log(a < b) // 누가 큰지 작은지

예시 2번

const a = 3
const b = 1
console.log(a >= b) // 크거나 같은지
const a = 1
const b = '1'
console.log(a === b) // false
console.log(a == b)  // true

🔥 정리

  • == (동등연산자)
    두 값의 모양이 같은지 비교 (잘사용하지않음)
  • ===
    값의 모양과 타입까지 비교
  • !=
    두 값이 다른지 비교
  • <
    한 값이 작은지 비교
  • >
    한 값이 큰지 비교
  • <=
    한 값이 작거나 같은지 비교
  • >=
    한 값이 크거나 같은지 비교

논리 연산자 (logical operator)

1) and(그리고) 연산자

전부 다 같은 값인 경우에 사용된다.

const a = 1 === 1
const b = 'AB' === 'AB'
const c = true
console.log('&&: ', a && b && c)

2) or(또는) 연산자

true 값이 하나 이상이면 true

const a = 1 === 1
const b = 'AB' === 'AB'
const c = false
console.log('!: ', !a)

3) not(부정) 연산자

true 값이 하나 이상이면 true

const a = 1 === 123
const b = 'AB' === 'AB'
const c = false
console.log('!: ', !a) // 반대값이 true, a 가 같지 않기때문에 true 가 나온다.

삼항 연산자 (ternary operator)

특정한 조건을 가지고서 코드의 내용을 실행할 수 있다.

const a = 1 < 2
// if (a) {
//	console.log('참')
// } else {
//	console.log('거짓')}
console.log(a ? '참' : '거짓')

전개 연산자 (spread)

특정한 조건을 가지고서 코드의 내용을 실행할 수 있다.

const fruits = ['Apple', 'Banana', 'Cherry', 'Orange'] // 배열데이터
console.log(fruits)
console.log(...fruits) // '문자데이터' 형식으로 출력

function toObject(a, b, ...c) { // ...c : rest parameter 나머지 매개변수(나머지를 다 받음)
	return {
    	a: a, // a 만 쳐도됨
      	b: b, // b
      	c: c // c
        // a, b, c 도 됨
    }
}
// const toObject = (a, b, ...c) => ({a, b, c}) 화살표함수로 표현하는 법, {} 겉에 ()를 감싸줘야 반복됨

console.log(toObject(...fruits))
//a: "Apple", b: "Banana", c: "Cherry" "Cherry"

getType

특정 데이터의 타입을 알 수 있다. (string, number, boolean ...)

console.log(typeof 'daldaro');
console.log(getType(123);

export default

main.js 파일을 제외하고 다른 파일들에서 (예를 들면) getType 을 동시에 적용하고 싶을 때 사용하는 방법

  • 새로운 파일 생성 (test.js 와 getType.js)
  • getType.js
export default function getType(data) {
    return Object.prototype.toString.call(data).slice(8, -1)
}
  • 다른 파일들 (main.js 와 test.js) 에 복사해준다.
import getType from "./getType";

console.log(getType(123)) // number
console.log(getType(false)) // boolean
console.log(getType(null)) // null
profile
나이들어서 공부함

0개의 댓글