JS 06 Array & Object

Seungju Hwang·2021년 1월 5일
0

JavaScript

목록 보기
6/13
post-thumbnail

Array & Object

Array

배열을 생성할 때 사용하는 리스트 형태의 고수준 객체

기본

const arrayNumbers = [1,2,3,4]
arrayNumbers[0]
arrayNumbers[-1] // 불가능
arrayNumbers.length // 4

reverse

arrayNumbers.reverse()
console.log(arrayNumbers) // [4,3,2,1]

push && pop

  • 숫자배열에 문자도 push 할 수 있음
arrayNumbers.push('a')
console.log(arrayNumbers) // [4,3,2,1,'a']
arrayNumbers.pop() //'a'
console.log(arrayNumbers) // [4,3,2,1]

unshift && shift

  • 배열 맨 앞에 값 넣기(빼기)
arrayNumbers.unshift('a')
console.log(arrayNumbers) // ['a',4,3,2,1]
arrayNumbers.shift() // 'a'
console.log(arrayNumbers) // [4,3,2,1]

include

  • 배열에 특정 요소가 있는 지 여부를 boolean값으로 변환
arrayNumbers.include(1) //true
arrayNumbers.include(100) // false

indexOf

  • 특정 요소가 있는 지 확인후, 있으면 해당 값의 인덱스를 반환
  • 없으면 -1을 반환
arrayNumbers.indexOf(2) // 2
arrayNumbers.indexOf(100) // -1

join

  • 인자를 기준으로 쭉 이어서 문자열로 반환
  • 인자가 없다면 콤마(,)를 기준으로 이어준다.
arrayNumbers.join() // 4,3,2,1
arrayNumbers.join('') // 4321
arrayNumbers.join('-') //4-3-2-1

Object

객체. key: value 로 구성된 자바스크립트 자료형 중 하나
key는 문자열 타입이고 value는 모든 타입이 가능!

기본

const person = {
  name:'sj',
  'phone number' : '010111111111',
  samsungProducts : {
    galaxyTab : 'galaxyTab S7',
    galaxyS20 : 'galaxy S20'
  }
}

person.name // sj
person['name'] // sj
person['phone number']  // sj
person.samsungProducts.galaxyTab //galaxyTab S7
// person.get() // 불가능..이건 파이썬 문법

Object 축약 문법(ES6+)

const books = ['Eloquent JS', 'JS Ninja']

const comics ={
	DC: ['Aquaman','Batman'],
	Marvel:['Avengers','Captain Marvel']
}

const bookShop = {
	books, //books : books
	comics //comics : comics
}

객체 내부의 함수 == 메서드

const baby = {
	name:'kobe',
	cook: function() {
	console.log('Hi, I cook!')
	}
}
baby.cook() // Hi, I cook!
  • 최신 문법
const baby = {
	name:'kobe',
	cook() {
	console.log('Hi, I cook!')
	}
}

baby.cook() // Hi, I cook!

Object Destructing

  • ES6+ 에서만 사용 가능한 문법
  • 객체에서 일부만 사용하고 싶을 때 유용하다.
const userInformation = {
	name:'sj',
	userId:'s1234',
	phoneNumber:'010-1111-1111',
	email:'sj@naver.com'
}

// -ES5까지 사용하던 방법
const name = userInformation.name
const userId = userInformation.userId

// -ES6+
const {name} = userInformation
const {name,userId,email} = userInformation
profile
기록하는 습관은 쉽게 무너지지 않아요.

0개의 댓글