[Java Script] Reference Type

Jingi·2024년 4월 18일

Web

목록 보기
27/40
post-thumbnail

함수

Function

  • 참조 자료형에 속하며 모든 함수는 Function Object

참조 자료형

  • Objects(Object, Array, Function)
  • 객체의 주소가 저장되는 자료형 (가변, 주소가 복사)

함수 구조

function name([parm[,parm,[...,parm]]]){
    statements
    return value
}
  • function 키워드
  • 함수의 이름
  • 함수의 매개변수
  • 함수의 body를 구성하는 statements
  • return 값이 없다면 undefined를 반환

함수 정의 2가지 방법

  • 선언식 (function declarartion)
function funcName(){
    statements
}
function add(num1, num2){
    return numl1 + num2
}
add(1, 2)
  • 표현식 (function expression)
const funcName = function (){
    statements
}
function sub(num1, num2){
    return numl1 - num2
}
sub(2, 1)

함수 표현식 특징

  • 함수 이름이 없는 익명함수를 사용할 수 있음
  • 선언식과 달리 표현식으로 정의한 함수는 호이스팅 되지 않으므로 함수를 정의하기 전에 먼저 사용할 수 없음

함수 표현식과 표현식 종합

()선언식표현식
특징익명 함수 사용 불가능
호이스팅 있음
익명함수 사용가능
호이스팅 없음
기타사용권장

매개변수 정의 방법

기본 함수 매개변수

  • 전달하는 인자가 없거나 undefined가 전달될 경우 이름 붙은 매개변수를 기본값으로 초기화
const greeting = function (name = 'Anonymous'){
    return `Hi ${name}`
}

greeting() // Hi Anonymous

나머지 매개변수

  • 임의의 수의 인자를 배열로 허용하여 가변인자를 나타내는 방법
  • 작성규칙
    • 함수 정의 시 나머지 매개변수는 하나만 작성할 수 있음
    • 나머지 매개변수는 함수 정의에서 매개변수 마지막에 위치해야 함
const myFunc = function (parm1, parm2, ....restPrams) {
    return [param1, param2, restPrams]
}

myFunc(1, 2, 3, 4, 5)// [1,2,[3,4,5]]
myFunc(1, 2) // [1,2,[]]

매개변수와 인자 개수가 불일치 할 때

  • 매개변수 개수 > 인자 개수

    • 누락된 인자는 undefined로 할당
      const threeArgs = function (param1, param2, param3){
          return [param1, param2, param3]
      }
      threeArgs() // [undefined, undefined, undefined]
      threeArgs(1) // [1, undefined, undefined]
      threeArgs(2, 3) // [2, 3, undefined]
  • 매개변수 < 인자개수

    • 초과 입력한 인자는 사용하지 않음

      const noArgs = function (){
          return 0
      }
      noArgs(1,2,3) // 0
      
      const twoArgs = function (param1, param2){
          return [param1, param2]
      }
      twoArgs(1,2,3) // [1,2]

Spread syntax

  • '...'
  • 전개 구문
    • 배열이나 문자열과 같이 반복 가능한 항목을 펼치는 것
    • 전개 대상에 따라 역할이 다름
      • 배열이나 객체의 요소를 개별적인 값으로 분리하거나 다른 배열이나 객체의 요소를 현재 배열이나 객체에 추가하는 등
  • 전개 구문 활용처
    • 함수와의 사용
      • 함수 호출 시 인자 확장
      • 나머지 매개변수(압축)
    • 객체와의 사용 (객체 파트에서 진행)
    • 배열과의 활용 (배열 파트에서 진행)

전개 구문 활용

  • 함수와의 사용

    • 함수 호출 시 인자 확장

      function myFunc(x,y,z){
          return x + y + z
      }
      
      let numbers = [1, 2, 3]
      
      console.log(myFunc(...numbers)) // 6
    • 나머지 매개변수 (압축)

      function myFunc2(x, y, ...restArgs){
          return [x, y, restArgs]
      }
      console.log(myFunc2(1,2,3,4,5)) // [1,2,[3,4,5]]
      console.log(myFunc2(1,2)) // [1,2,[]]

화살표 함수 표현식

  • 함수 표현식의 간결한 표현법
const arrow = function (name){
    return `hello, ${name}`
}

const arrow = name => `hello, ${name}`

화살표 함수 작성 과정

  • function 키워드 제거 후 매개변수와 중괄호 사이에 화살표 작성

    const arrow1 = function (name){
        return `hello, ${name}`
    }
    
    const arrow2 = (name) => {return `hello, ${name}`}
  • 함수의 매개변수가 하나 뿐이라면, 매개변수의 '()'제거 가능

    const arrow1 = function (name){
        return `hello, ${name}`
    }
    
    // 1. function 키워드 삭제 후 화살표 작성
    const arrow2 = (name) => {return `hello, ${name}`}
    
    // 2. 인자가 1개일 경우에만 () 생략 가능
    const arrow3 = name => {return `hello, ${name}`}
  • 함수 본문의 표현식이 한 줄이라면, '{}'와 'return' 제거 가능

    const arrow1 = function (name){
        return `hello, ${name}`
    }
    
    // 1. function 키워드 삭제 후 화살표 작성
    const arrow2 = (name) => {return `hello, ${name}`}
    
    // 2. 인자가 1개일 경우에만 () 생략 가능
    const arrow3 = name => {return `hello, ${name}`}
    
    // 3. 함수 본문이 return을 포함한 표현식 1개일 경우에 {} & return 삭제 가능
    const arrow4 = name => `hello, ${name}`

화살표 함수 심화

// 1. 인자가 없다면 () or _로 표시 가능
const noArgs = () => 'No args'
const noArgs = _ => 'No args'

// 2-1. object를 return 한다면 return을 명시적으로 작성
const returnobject1 = () => (return {key:'value'})

// 2-2. return을 작성하지 않으려면 객체를 소괄호로 감싸야한다
const returnobject2 = () => ({key:'value'})

객체

Object

  • 키로 구분된 데이터 집합을 저장하는 자료형(data collection)

객체 구조

  • 중괄호('{}')를 이용해 작성
  • 중괄호 안에는 key:value 쌍으로 구성된 속성를 여러 개 작성 가능
  • key는 문자형만 허용
  • value는 모든 자료형 허용
    const user = {
        name :'Alice',
        'key with space' : true,
        greeting: function(){
            return 'hello'
        }
    }

속성참조

  • 점('.') 또는 대괄호('[]')로 객체 요소 접근

  • key 이름에 띄어쓰기 같은 구분자가 있으면 대괄호 접근만 가능

    // 조회
    console.log(user.name) // Alice
    console.log(user['key with space']) // true
    
    // 추가
    user.address = 'korea'
    console.log(user) // {name:'Alice', key with space : true, address:'korea', greeting:f}
    // 수정
    user.name = 'Bella' // Bella
    console.log(user.name) // Bella
    
    // 삭제
    delete user.name
    console.log(user) // {key with space : true, address:'korea', greeting:f}

in 연산자

  • 속성이 객체에 존재하는지 여부를 확인
    console.log('greeting' in user) // true
    console.log('country' in user) // false

객체와 함수

Method

  • 객체 속성에 정의된 함수
    • this 키워드를 사용해 객체에 대한 특정한 작업을 수행 할 수 있음

Method 사용 예시

  • object.method() 방식으로 호출
  • 메서드는 객체를 행동 할 수 있게 함
    • console.log(user.greeting()) // hello

this keyword

  • 함수나 메서드를 호출한 객체를 가리키는 키워드
    • 함수 내에서 객체의 속성 및 메서드에 접근하기 위해 사용

method & this 사용예시

const person = {
    name : 'Alice',
    greeting: function(){
        return 'Hello ny name is ${this.name}'
    },
}

console.log(person.greeting()) // Hello my name is Alice

함수 호출 방법

호출 방법대상
단순호출전역 객체
메서드 호출메서드를 호출한 객체

단순 호출 시 this

  • 가리키는 대상 => 전역 객체
    const myFunc = function(){
        return this
    }
    console.log(myFunc()) // window

메서드 호출 시 this

  • 가리키는 대상 => 메서드를 호출한 객체
const myObj = {
    data : 1,
    myFunc : function(){
        return this
    }
}

console.log(myObj.myFunc()) // myObj

JavaScript this 정리

  • JavaScript의 함수는 호출될 때 this를 암묵적으로 전달 받음
  • JavaScript에서 this는 함수가 호출되는 방식에 따라 결정되는 현재 객체를 나타냄
  • Python의 self와 Java의 this가 선언시 이미 값이 정해지는 것에 비해 JavaScript의 this는 함수가 호출되기 전까지 값이 할당되지 않고 호출 시에 결정됨 (동적 할당)
  • this가 미리 정해지지 않고 호출 방식에 의해 결정됨
  • 장점
    • 함수(메서드)를 하나만 만들어 여러 객체에서 재사용할 수 있다는 것
  • 단점
    • 이런 유연함이 실수로 이어질 수 있다는 것
  • 개발자는 this의 동작 방식을 충분히 이해하고 장점을 취하면서 실수를 피하는데에 집중

단축속성

  • 키 이름과 값으로 쓰이는 변수의 이름이 같은 경우 단축 구문을 사용할 수 있음
// 사용 전
const name = 'Alice'
const age = 30

const user = {
    name: name,
    age: age,
}

const myObj1 = {
    myFunc:function(){
        return 'Hello'
    }
}
// 사용 후
const name = 'Alice'
const age = 30

const user = {
    name,
    age,
}

const myObj1 = {
    myFunc(){
        return 'Hello'
    }
}

계산된 속성

  • 키가 대괄호로 둘러싸여 있는 속성
    • 고정된 값이 아닌 변수 값을 사용할 수 있음
const product = prompt('물건 이름을 입력해주세요')
const prefix = 'my'
const suffix = 'property'

const bag = {
    [product] : 5,
    [prefix + suffix]: 'value',
}

console.log(bag) // {연필 : 5, myproperty: 'value'}

구조 분해 할당

// 적용 전
const userInfo = {
    firstname:'Alice',
    userId : 'alice123',
    email : 'alice@gmail.com'
}

const firstName = userInfo.name
const userId = userInfo.userId
const email = userInfo.email
// 적용 후
const userInfo = {
    firstname:'Alice',
    userId : 'alice123',
    email : 'alice@gmail.com'
}

const {firstName} = userInfo
const {firstName, userId} = userInfo
const {firstName, userId, email} = userInfo

console.log(firstName, userId, email)

구조 분해 할당 활용

  • 함수의 매개변수로 객체 구조 분해 할당 활용 가능
const person = {
    name:'Bob',
    age: 35,
    city:'London',
}

function printInfo({name, age, city}){
    console.log('이름:${name}, 나이:${age}, 도시:${city}')
}

printInfo(person) // 이름 : Bob, 나이: 35, 도시: London

Object with 전개구문

  • 객체 복사
    • 객체 내부에서 객체 전개
  • 얕은 복사에 활용 가능
const obj = {b:2, c:3, d:4}
const newObj = {a:1, ...obj, e:5}

console.log(newObj) // {a:1, b:2, c:3, d:4, e:5}

유용한 객체 메서드

  • Object.keys()
  • Object.values()
const profile = {
    name:'Alice',
    age:30,
}
console.log(Object.keys(profile)) // ['name', 'age']

console.log(Object.values(profile)) // ['Alice', 30]

Optional chaining

Optional chaining

  • 속성이 없는 중첩 객체를 에러 없이 접근할 수 있는 방법
  • 만약 참조 대상이 null 또는 undefined라면 에러가 발생하는 것 대신 평가를 멈추고 undefined를 반환
const user = {
    name : 'Alice',
    greeting: function (){
        return 'hello'
    }
}

console.log(user.address.street) // Uncaught TypeError
console.log(user.address?.street) // Undefined

console.log(user.nonMethod()) // Uncaught TypeError
console.log(user.nonMethod?.()) // Undefined
  • 만약 Optional chaining을 사용하지 않는다면 다음과 같인 '&&' 연산자를 사용
const user = {
    name : 'Alice',
    greeting: function (){
        return 'hello'
    }
}
console.log(user.address && user.address.street) // undefined

Optional chaining 장점

  • 참조가 누락될 가능성이 있는 경우 연결된 속성으로 접근할 때 더 짧고 간단한 표현식을 작성할 수 있음
  • 어떤 속성이 필요한지에 대한 보증이 확실하지 않는 경우에 객체의 내용을 보다 편리하게 탐색할 수 있음

Optional chaining 주의 사항

  • Optional chaining은 존재하지 않아도 괜찮은 대상에만 사용해야 함
    • 왼쪽 대상이 없어도 괜찮은 경우에만 선택적으로 사용
    • 중첩 객체를 에러 없이 접근하는 것이 사용 목적이기 때문
// 이전 예씨 코드에서 user 객체는 논리상 반드시 있어야 하지만 address는 필수 값이 아님
// user에 값을 할당하지 않은 문제가 있을 때 바로 알아낼 수 있어야 하기 때문

// Bad
user?.address?.street

// Good
user.address?.street
  • Optional chaining 앞의 변수는 반드시 선언되어 있어야 함
console.log(myObj?.address) // Uncaught ReferenceError: myObj is not defined

Optional chaining 정리

  • obj?.prop
    • obj가 존재하면 obj.prop을 반환하고, 그렇지 않으면 undefined를 반환
  • obj?.[prop]
    • obj가 존재하면 obj[prop]을 반환하고, 그렇지 않으면 undefined를 반환
  • obj?.method()
    • obj가 존재하면 obj.method()를 호출하고, 그렇지 않으면 undefined를 반환

JSON

JSON

  • JavaScript object Notation
  • key-value 형태로 이루어진 자료 표기법
  • JavaScript의 Object와 유사한 구조를 가지고 있지만 JSON은 형식이 있는 문자열
  • JavaScript에서 JSON을 사용하기 위해서는 Object 자료형으로 변경해야 함

Object <-> JSON 변환하기

const jsObject = {
    coffee:'Americano',
    iceCream: 'Cookie and cream',
}
// Object -> JSON
const objToJson = JSON.stringify(jsObject)
console.log(objToJson) // {"coffee":'Americano', "iceCream": 'Cookie and cream'}
console.log(typeof objToJson) // string
// JSON -> Object
const jsonToObj = JSON.parse(objToJson)
console.log(jsonToObj) // {coffee:'Americano', iceCream: 'Cookie and cream'}
console.log(typeof jsonToObj) // object

new 연산자

  • new constructor[([argument])]
    • 사용자 정의 객체 타입을 생성
    • 매개변수
      • constructor: 객체 인스턴스의 타입을 기술하는 함수
      • arguments: constructor와 함께 호출된 값 목록
function Member(name, age, sId){
    this.name = name
    this.age = age
    this.sId = sId
}

const member3 = new Member('Bella', 21, 20226543)

console.log(member3) // Member { name: 'Bella', age:21, sId:20226543}
console.log(member3.name) // Bella

배열

Object

  • 키로 구분된 데이터 집합을 저장하는 자료형
    • 이제는 순서가 있는 collection이 필요

Array

  • 순서가 있는 데이터 집합을 저장하는 자료구조

배열 구조

  • 대괄호를 이용해 작성
  • 요소 자료형 : 제약 없음
  • length 속성을 사용해 배열에 담긴 요소가 몇 개인지 알 수 있음
const names = ['Alice', 'Bella', 'Cathy']

console.log(names[0]) // Alice
console.log(names[1]) // Bella
console.log(names[2]) // Cathy

console.log(names.length) // 3

주요 메서드

메서드역할
push / pop배열 끝 요소를 추가 / 제거
unshift / shift배열 앞 요소를 추가 / 제거

push()

  • 배열 끝에 요소를 추가
const names = ['Alice', 'Bella', 'Cathy']
names.push('Dan')
console.log(names[3]) // Dan

pop()

  • 배열 끝에 요소를 제거하고 제거한 요소를 반환
const names = ['Alice', 'Bella', 'Cathy']
console.log(names.pop()) // Cathy
console.log(names) // ['Alice', 'Bella']

unshift()

  • 배열 앞 요소를 추가
names.unshift('Eric')
console.log(names) // ['Eric', 'Alice', 'Bella', 'Cathy']

shift()

  • 배열 앞 요소를 제거하고 제거한 요소를 반환
const names = ['Alice', 'Bella', 'Cathy']

console.log(names.shift()) // Alice
console.log(names) // ['Bella', Cathy]

Array Helper Methods

  • 배열 조작을 보다 쉽게 수행할 수 있는 특별한 메서드 모음
  • ES6에 도입
  • 배열의 각 요소를 순회하며 각 요소에 대해 함수(콜백함수)를 호출
    • forEach(), map(), filter(), every(), some(), reduce() 등
  • 메서드 호출 시 인자로 함수를 받는 것이 특징

콜백함수

  • 다른 함수에 인자로 전달되는 함수
    • 외부 함수 내에서 호출되어 일종의 루틴이나 특정 작업을 진행
const numbers1 = [1, 2, 3]
numbers1.forEach(function (num) {
    console.log(num ** 2)
})
// 1
// 4
// 9
const numbers2 = [1, 2, 3]
const callBackFunction = function (num) {
    console.log(num ** 2)
}
numbers2.forEach(callBackFunction)

// 1
// 4
// 9

주요 Array Helper Methods

메서드역할
forEach- 배열 내의 모든 요소 각각에 대해 함수를 호출
- 반환 값 없음
map- 배열 내의 모든 요소 각각에 대해 함수를 호출
- 함수 호출 결과를 모아 새로운 배열을 반환

forEach()

  • 배열의 각 요소를 반복하며 모든 요소에 대해 함수를 호출
  • arr.forEach(callback(item[, index[, array]]))
arr.forEach(function(item, index, array){

})
  • 콜백함수는 3가지 매개변수로 구성
    • item : 처리할 배열의 요소
    • index : 처리할 배열 요소의 인덱스 (선택 인자)
    • array : forEach를 호출한 배열 (선택 인자)
  • 반환 값
    • undefined

map()

  • 배열의 모든 요소에 대해 함수를 호출하고, 반환 된 호출 결과 값을 모아 새로운 배열을 반환
  • arr.map(callback(item[, index[, array]]))
  • forEach의 매개변수와 동일
  • 반환 값
    • 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열
    • forEach 동작원리와 같지만 forEach와 달리 새로운 배열을 반환함
const newArr = array.map(function(item, index, array))
  • forEach의 매개 변수와 동일
  • 반환 값
    • 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열
    • forEach 동작 원리와 같지만 forEach와 달리 새로운 배열을 반환함
const names = ['Alice', 'Bella', 'Cathy']

const result3 = names.map(function (name){
    return name.length
})

const result4 = names.map((name) => {
    return name.length
})

console.log(result3) // [5, 5, 5]
console.log(result4) // [5, 5, 5]
const names = ['Alice', 'Bella', 'Cathy']

// for loop
for (let idx = 0 ; idx <names.length; idx++){
    console.log(names[idx])
}

// for...of
for (const name of names){
    console.log(name)
}

// for Each
names.forEach((name) => {
    console.log(name)
})
방식특징
for loop- 배열의 인덱스를 이용하여 각 요소에 접근
- break, continue 사용 가능
for ...of- 배열 요소에 바로 접근 가능
- break, continue 사용가능
forEach- 간결하고 가독성이 높음
- callback 함수를 이용하여 각 요소를 조작하기 용이
- break, continue 사용 불가능
profile
데이터 분석에서 백엔드까지...

0개의 댓글