Jin's Dev Story

[JavaScript] 객체 본문

Programming Language/JavaScript

[JavaScript] 객체

woojin._. 2024. 6. 12. 09:06
  • 객체 : 실제로 존재하는 사물
  • 속성 : 이름과 값으로 구성
    • ex ) 이름 : 구름, 나이 : 7살, 산책하기(), 밥 먹기() → 모두 속성으로 산책하기(), 밥 먹기()는 속성 중에 동작(함수)인 것으로 메소드라고 한다.

객체

  • 키 : 값
<script>
	const product = {
		제품명: '7D 건조 망고',
		유형: '당절임',
		성분: '망고, 설탕, 메타중아황산나트륨, 치자황색소',
		원산지: '필리핀'
	}
</script>
  • 객체 뒤에 대괄호 사용하고 키를 입력하면 요소에 접근 가능
product['제품명']  -> '7D 건조 망고'
product['유형']    -> '당절임'
product['성분']    -> '망고, 설탕, 메타중아황산나트륨, 치자황색소'
product['원산지']  -> '필리핀'
  • 온점( . )도 사용 가능
product.제품명   -> '7D 건조 망고'
product.유형     -> '당절임'
product.성분     -> '망고, 설탕, 메타중아황산나트륨, 치자황색소'
product.원산지   -> '필리핀'

속성과 메소드

  • 요소 : 배열 내부에 있는 값
  • 속성 : 객체 내부에 있는 값
    • 속성은 모든 형태의 자료형을 가질 수 있다.
  • 메소드 : 객체의 속성 중 함수 자료형이 속성
<script>
	const pet = {
		name: '구름',
		eat: function (food) { }
	}

	// 메소드를 호출한다.
	pet.eat()
</script>

this 키워드

  • 자기 자신이 가진 속성이라는 것을 표시할 때 사용
<script>
	const pet = {
		name: '구름',
		eat: function (food) {
			alert(this.name + '은/는' + food + '을/를 먹습니다.')
		}
	}

	// 메소드를 호출합니다.
	pet.eat('밥')
</script>

// 실행 결과
// 구름은/는 밥을/를 먹습니다.

동적으로 객체 속성 추가/제거

  • 객체 생성 이후에 속성을 추가하거나 제거하는 것
  • 추가
    • 객체를 생성한 후 속성을 지정하고 값을 입력하면 됨
    <script>
    	const student = {}
    	student.이름 = '윤인성'
    	student.취미 = '악기'
    	student.장래희망 = '생명공학자'
    
    	console.log(JSON.stringify(student, null, 2))
    </script>
    
    // 실행 결과
    // {
    //		"이름": "윤인성",
    //		"취미": "악기",
    //		"장래희망": "생명공학자"
    //	}
  • 삭제
    • delete 객체.속성
    <script>
    	const student = {}
    	student.이름 = '윤인성'
    	student.취미 = '악기'
    	student.장래희망 = '생명공학자'
    
    	delete student.장래희망
    
    	console.log(JSON.stringify(student, null, 2))
    </script>
    
    // 실행 결과
    // {
    //		"이름": "윤인성",
    //		"취미": "악기"
    //	}

메소드 간단 선언 구문

<script>
	const pet = {
		name: '구름',
		eat (food) {
			alert(this.name + '은/는' + food + '을/를 먹습니다.')
		}
	}

	// 메소드를 호출합니다.
	pet.eat('밥')
</script>

// 실행 결과
// 구름은/는 밥을/를 먹습니다.

객체 자료형

  • 객체 : 속성과 메소드를 가질 수 있는 모든 것 ex) 객체
  • 배열도 속성을 가질 수 있다.
> const a = []
undefined

> a.sample = 10
10

> a.sample
10

> typeof a
"object"

> Array.isArray(a)
true
  • 함수도 객체를 가질 수 있다.
    • 함수는 실행이 가능한 객체라는 특이한 자료로 typeof 연산자를 사용해서 자료형을 확인하면 object가 아닌 function을 출력하므로 객체의 특성을 완벽하게 가지고 있으므로 일급객체라고도 한다.
> function b () {}
undefined 

> b.sample = 10
10

> b.sample
10

> typeof b
"function"

기본 자료형

  • 실체가 있는 것 중에서 객체가 아닌 것
  • 숫자, 문자열, 불
  • 객체가 아니므로 속성을 가질 수 없다.
> const c = 273
undenfined

> c.sample = 10
10

> c.sample
undefined    // 속성을 만들 수 있는 것처럼 보이지만 실제로는 만들어지지 않는다.

> const d = '안녕하세요'
undefined

> d.sample = 10
10

> d.sample
undefined

기본 자료형을 객체로 선언하기

  • Number, String, Boolean 함수 사용
const 객체 = new 객체 자료형 이름()

new Number(10)
new String('안녕하세요')
new Boolean(true)
> const f = new Number(273)
undefined

> typeof f
"object"

> f.sample = 10

> f.sample
10

> f
Number {273, sample : 10}

> f + 0
273

> f.valueOf()
273

프로토타입으로 메소드 추가하기

객체 자료형 이름.prototype.메소드 이름 = function () {

}
> Number.prototype.sample = 10
10

> const i = 273
undefined

> i.sample
10

제곱 연산자(**)

> 2 ** 2
4

> 2 ** 3
8

> 2 ** 4
16
<script>
	Number.prototype.power = function (n = 2) {
		return this.valueOf() ** n
	}

	const a = 12
	console.log('a.power():', a.power())
	console.log('a.power(3):', a.power(3))
	console.log('a.power(4):', a.power(4))
</script>

// 실행 결과
// a.power(): 144
// a.power(3): 1728
// a.power(4): 20736

indexOf()

  • 해당 문자열이 시작하는 위치(인덱스)를 출력하고, 없으면 -1을 출력한다.
> const j = '안녕하세요'
undefined

> j.indexOf('안녕')
0

> j.indexOf('하세')
2

> j.indexOf('없는 문자열')
-1

// 배열의 indexOf()
> const k = [1, 2, 3]
undefined

> k.indexOf(2)
1

> k.indexOf(3)
2

> k.indexOf(100)
-1

contain()

  • 문자열 내부에 문자열이 포함되어 있는지 여부를 구한다.
<script>
	String.prototype.contain = function (data) {
		return this.indexOf(data) >= 0
	}

	Array.prototype.contain = function (data) {
		return this.indexOf(data) >= 0
	}

	const a = '안녕하세요'
	console.log('안녕 in 안녕하세요:', a.contain('안녕'))
	console.log('없는데 in 안녕하세요:', a.contain('없는데'))

	const b = [273, 32, 103, 57, 52]
	console.log('273 in [273, 32, 103, 57, 52]:', b.contain(273))
	console.log('0 in [273, 32, 103, 57, 52]:', b.contain(0))
</script>

// 실행 결과
// 안녕 in 안녕하세요: true
// 없는데 in 안녕하세요: false
// 273 in [273, 32, 103, 57, 52]: true
// 0 in [273, 32, 103, 57, 52]: false

Number 객체

  • 숫자 N번째 자릿수까지 출력하기 : toFixed()
> const l = 123.456789
undefined

> l.toFixed(2)
"123.46"

> l.toFixed(3)
"123.457"

> l.toFixed(4)
"123.4568"
  • NaN과 Infinity 확인하기 : isNaN(), isFinite()
    • NaN - NaN인지 여부 확인
      • 비교 연산자로 비교 불가
      > const m = Number('숫자로 변환할 수 없는 경우')
      undefined
      
      > m
      NaN
      
      > m === NaN
      false
      
      > Number.isNaN(m)
      true
      
    • Infinity - 값이 유한한 숫자인지 여부를 확인
      • 비교 연산자로 비교 가능
      > const n = 10 / 0
      undefined
      
      > n
      Infinity
      
      > const o = -10 / 0
      undefined
      
      > o
      -Infinity
      
      > Number.isFinite(n)
      false
      
      > Number.isFinite(o)
      false
      
      > Number.isFinite(1)
      true
      
      > Number.isFinite(10)
      true
      

String 객체

  • 문자열 양쪽 끝의 공백 없애기: trim()
> const stringA = `
메시지를 입력하다보니 앞에 줄바꿈도 들어가고`
undefined

> const stringB = `     앞과 뒤에 공백도 들어가고     `
undefined

> stringA
"
메시지를 입력하다보니 앞에 줄바꿈도 들어가고"

> stringB
"     앞과 뒤에 공백도 들어가고     "

> stringA.trim()
"메시지를 입력하다보니 앞에 줄바꿈도 들어가고"

> stringB.trim()
"앞과 뒤에 공백도 들어가고"
  • 문자열을 특정 기호로 자르기: split()
> let input = `
일자,달러,엔,유로
02,1141.8,1097.46,1262.37
03,1148.7,1111.36,1274.65
`
undefined

> input = input.trim()
"일자,달러,엔,유로
02,1141.8,1097.46,1262.37
03,1148.7,1111.36,1274.65"

> input = input.split('\\n')
["일자,달러,엔,유로", "02,1141.8,1097.46,1262.37", "03,1148.7,1111.36,1274.65"]

> input = input.map((line) => line.split(','))
[Array(4), Array(4), Array(4)]

> JSON.stringify(input, null, 2)
"[
 [
  "일자",
	"달러",
	"엔",
	"유로"
 ],
 [
	"02",
	"1141.8",
	"1097.46",
	"1262.37",
 ],
 [
	"03",
	"1148.7",
	"1111.36",
	"1274.65"
 ]
 ]"

JSON 객체

  • JSON.stringify() → 자바스크립트 객체를 JSON 문자열로 변환할 때
    • 2번째 매개변수는 객체에서 어떤 속성만 선택해서 추출하고 싶을 때 사용하나 거의 사용하지 않으며, 일반적으로 null을 넣는다.
    • 3번째 매개변수는 들여쓰기 2칸으로 설정한다.
<script>
	const data = [{
		name: '혼자 공부하는 파이썬',
		price: 18000,
		publisher: '한빛미디어'
	}, {
		name: 'HTML5 웹 프로그래밍 입문',
		price: 26000,
		publisher: '한빛아카데미'
	}]

	console.log(JSON.stringify(data))
	console.log(JSON.stringify(data, null, 2))  
</script>

// 실행 결과
// [{"name": "혼자 공부하는 파이썬","price": 18000,"publisher": "한빛미디어"}, {"name": "HTML5 웹 프로그래밍 입문","price": 26000,"publisher": "한빛아카데미"}]
// [
//   {
//      "name": "혼자 공부하는 파이썬",
// 		  "price": 18000,
// 		   "publisher": "한빛미디어"
// 	 }, 
//   {
//      "name": "HTML5 웹 프로그래밍 입문",
// 		  "price": 26000,
// 		   "publisher": "한빛아카데미"
// 	 }
// ]
  • JSON.parse() → JSON 문자열을 자바스크립트 객체로 전개할 때
<script>
	const data = [{
		name: '혼자 공부하는 파이썬',
		price: 18000,
		publisher: '한빛미디어'
	}, {
		name: 'HTML5 웹 프로그래밍 입문',
		price: 26000,
		publisher: '한빛아카데미'
	}]

	const json = JSON.stringify(data)
	console.log(json)

	console.log(JSON.parse(json))  
</script>

// 실행 결과
// [{"name": "혼자 공부하는 파이썬","price": 18000,"publisher": "한빛미디어"}, {"name": "HTML5 웹 프로그래밍 입문","price": 26000,"publisher": "한빛아카데미"}]
// Array(2)
//   0: {"name": "혼자 공부하는 파이썬","price": 18000,"publisher": "한빛미디어"}
//   1: {"name": "HTML5 웹 프로그래밍 입문","price": 26000,"publisher": "한빛아카데미"}
//   length: 2
//   __proto__: Array(0)

Math 객체

  • Math.sin(), Math.cos(), Math.tan()
> Math.PI
3.141592653589793

> Math.E
2.718281828459045
  • Math.random()
<script>
	const num = Math.random()
	    
	console.log('# 랜덤한 숫자')
	console.log("0-1 사이 랜덤한 숫자: ", num)
	console.log('')

	console.log('# 랜덤한 숫자 범위 확대')
	console.log("0~10 사이 랜덤한 숫자: ", num * 10)
	console.log("0~50 사이 랜덤한 숫자: ", num * 50)
	console.log('')

	console.log('# 랜덤한 숫자 범위 이동')
	console.log("-5~5 사이 랜덤한 숫자: ", num * 10 - 5)
	console.log("-25~25 사이 랜덤한 숫자: ", num * 50 - 25)
	console.log('')

	console.log('# 랜덤한 정수 숫자')
	console.log("-5~5 사이 랜덤한 정수 숫자: ", Math.floor(num * 10 - 5))
	console.log("-25~25 사이 랜덤한 정수 숫자: ", Math.floor(num * 50 - 25))
	console.log('')
</script>

// 실행 결과
// # 랜덤한 숫자
// 0-1 사이 랜덤한 숫자: 0.56234851654

// # 랜덤한 숫자 범위 확대
// 0~10 사이 랜덤한 숫자: 0.75354653215
// 0~50 사이 랜덤한 숫자: 3.45131644565

// # 랜덤한 숫자 범위 이동
// -5~5 사이 랜덤한 숫자: -4.135465433213
// -25~25 사이 랜덤한 숫자: -21.6513165464

// # 랜덤한 정수 숫자
// -5~5 사이 랜덤한 정수 숫자: -5
// -25~25 사이 랜덤한 정수 숫자: -22