객체 | 배열 | |
---|---|---|
요소 접근 시 | 키 사용 | 인덱스 사용 |
const prod = {
제품명 : '7D 건조 망고',
유형 : '당절임',
성분 : '망고, 설탕, 메타중아황산나트륨, 치자황색소',
원산지 : '필리핀'
}
prod['제품명']
prod['유형']
prod['성분']
prod['원산지']
배열 | 객체 |
---|---|
요소 | 속성 |
const obj = {
number : 273,
string : '구름',
boolean : true,
array : [52, 273, 103, 32],
method : function(){}
}
메소드 : 객체의 속성 중 함수 자료형인 속성
const pet = {
name : '구름',
eat : function(food){}
}
//메소드 호출
**pet.eat()**
this : 자기 자신이 가진 속성이라는 것을 표시할 때
//변수 선언
const pet = {
name : '구름',
eat : function(food){
alert(**this**.name + '은/는 ' + food + '을/를 먹습니다.')
}
}
pet.eat('밥')
동적으로~ : 객체 처음에 생성 후에 속성 추가하거나 제거할 때
//객체 선언
const student = {}
**student.이름 = '한승연',
student.취미 = 'iceskating',
student.장래희망 = '돈 많은 사람'**
//출력
console.log(JSON.stringify(student,null,2))
delete 객체.속성
//객체 선언
const student = {}
student.이름 = '한승연',
student.취미 = 'iceskating',
student.장래희망 = '돈 많은 사람'
//객체 속성 제거
**delete student.장래희망**
//출력
console.log(JSON.stringify(student, null, 2))
//변수 선언
const pet = {
name : '구름',
eat (food){
alert(this.name + '은/는 ' + food + '을/를 먹습니다')
}
}
pet.eat('밥')
//객체 선언하기
const sth = {
name : '혼자 공부하는 파이썬',
price : 18000,
publisher : '한빛미디어'
}
console.log(sth)
메소드 : 객체의 속성 중 **함수 자료형**인 속성이므로, `print`임
실행 결과 : 빵은 스페인어로 pan입니다.
Array.isArray()
: 배열인지 확인하기
숫자, 문자열, 불 등 ⇒ 객체가 아니므로 속성을 가질 수 X
const c = 273
c.sample = 19 //undefined
const 객체 = new 객체 자료형 이름 ()
ex)
new Number(10)
new String('안녕하세요')
new Boolean(true)
JS는 편리성을 위해 기본 자료형의 속성과 메소드를 호출 시 일시적으로 기본 자료형을 객체로 승급시킴
prototype : 객체 전용 옷들
prototype 객체에 속성과 메소드를 추가하면 → 모든 객체에서 해당 속성과 메소드를 사용 가능
객체 자료형 이름.prototype.메소드 이름 = function() {}
Number.prototype.sample = 10
const i = 273
i.sample //=> 10
//power 메소드 추가하기
Number.prototype.power = function(n = 2){
return this.valueOf() ** n
}
//Number 객체의 power() 메소드를 사용
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))
valueOf()
: 객체 내부에서 값을 꺼내 쓰는 것임을 명확하게 하기 위해
indexOf()
: 문자열 내부에 어떤 문자열이 있는지, 배열 내부에 어떤 자료가 있는지 확인하기 위해
const i = '안녕하세여'
i.indexOf('안녕') //0
i.indexOf('하세') //1
i.indexOf('이건 없지') //-1 (존재하지 않으면 -1 출력 )
문자열.contain(문자열)
: 문자열 내부에 어떤 문자열이 포함되어 있는지 true or false
//contain() 메소드 추가하기
String.prototype.contain = function (data) {
return this.indexOf(data) >= 0
}
Array.prototype.contain = function (data) {
return this.indexOf(data) >= 0
}
//string 객체의 contain() 메소드를 사용
const a = '안녕하세요'
console.log('안녕 in 안녕하세요:', a.contain('안녕')) //true
console.log('없는데 in 안녕하세요:', a.contain('없는데')) //false
//array 객체의 contain() 메소드 사용
const b = [273,32,103,57,52]
console.log('273 in [273,32,103,57,52]', b.contain(273)) //true
console.log('0 in [273,32,103,57,52]', b.contain(0)) //false
toFixed()
const l = 123.456789
l.toFixed(2) //2자리까지
l.toFixed(3) //3자리까지
l.toFixed(4) //4자리까지
isNaN()
, isFinite()
isNaN()
const m = Number('숫자로 변환 불가') //undefined
m //NaN 생성
m === NaN ///false -> NaN과 비교해서는 NaN인지 아닌지 확인이 불가능함
Number.isNaN(m) //true
**isFinite()**
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(52362876) //true
trim()
문자열 앞뒤 공백 (띄어쓰기, 줄바꿈 등) 제거 가능
const a = `
앞에 줄바꿈`
const b = ` 앞이랑 뒤에 공백 `
a.trim() //앞에 줄바꿈
b.trim() //앞이랑 뒤에 공백
split()
문자열을 매개변수 (다른 문자열)로 잘라서 배열을 리턴하는 메소드
let input = `
일자, 달러, 엔, 유로
02, 1141.8, 1097.46, 1262.37
03, 1148.7, 1111.36, 1274.65
04, 1212.3, 1234.81, 2891.83
07, 1213.5, 1332.43, 1121.8
08, 1932.4, 1945.32, 1362.93
`
//앞뒤 공백 제거
input = input.trim()
//줄바꿈으로 자르기
input = input.split('\n')
input = input.map((line) => line.split(','))
JSON.stringify(input, null, 2)
인터넷에서 문자열로 데이터를 주고 받을 때 다양한 자료 표현 방식을 사용하는데, 현재 가장 많이 사용되는 방식 : JSON (JavaScript Object Notation)
JSON.stringify()
JS 객체를 JSON 문자열로 변환할 때
//자료 생성
const data = [{
name : '승연님 존예',
price : 7129128131827312,
publisher : '한승연'
}, {
name : '승연님',
price : 345678903427864,
publisher : '한승연'
}]
//자료를 JSON으로 변환
console.log(JSON.stringify(data)) //매개변수를 하나만 넣으면 한 줄로 변환
console.log(JSON.stringify(data, null, 2)) //2번째 매개변수는 객체에서 어떤 속성만 선택해서 추출하고 싶을 때 사용하나 거의 사용 X, 일반적으로 null 사용
//들여쓰기 2칸
JSON.parse()
JSON 문자열을 자바스크립트 객체로 전개
//자료 생성
const data = [{
name : '승연님 존예',
price : 7129128131827312,
publisher : '한승연'
}, {
name : '승연님',
price : 345678903427864,
publisher : '한승연'
}]
//자료를 JSON으로 변환
const json = JSON.stringify(data)
console.log(json)
//JSON 문자열을 다시 js 객체로 변환
console.log(JSON.parse(json))
## 6.2.9. Math 객체
수학과 관련된 기본적인 연산
pi, e 등 수학 상수, Math.sin(), Math.cos(), Math.tan() 등 삼각함수 존재
### `Math.random()` : 0이상 1이하 랜덤한 숫자 생성
```jsx
const num = Math.random()
console.log('랜덤 숫자')
console.log('0-1 사이 랜덤 숫자:', num)
console.log('랜덤 숫자 범위 확대하기')
console.log('0-10 사이 랜덤 숫자: ', num * 10)
console.log('0-50 사이 랜덤 숫자: ', num * 50)
console.log('랜덤 숫자 범위 이동')
console.log('-5 - 5 사이 랜덤 숫자: ', num * 10 - 5)
console.log('-25 - 25 사이 랜덤 숫자: ', num * 50 - 25)
<script src = “ “></script>
개발할 때 보조적으로 사용하는 함수들을 제공하는 라이브러리 중 하나, 최근 많이 사용됨
sortBy()
: 지정한 것으로 배열을 정렬해서 리턴해줌//데이터 생성
const data = [{
name : 'red queen',
price : 11,
publisher : '한승연'
}, {
name : 'glass sword ',
price : 3,
publisher : '한승연'
}, {
name : 'kings cage',
price : 6,
publisher : '한승연'
}, {
name : 'cruel crown',
price : 24243,
publisher : '한승연'
}]
//가격으로 정렬한 뒤 출력
const output = _.sortBy(data, (data)=> data.price)
console.log(JSON.stringify(output, null, 2))
function printLang(code) {
return printLang._lang[code]
}
printLang._lang = {
ko : '한국어',
en : '영어',
ja : '일본어',
fr : '프랑스어',
es : '스페인어'
}
console.log(printLang('ko')) //한국어
console.log(printLang('en')) //영어
const degree= 90
//출력
const radians = (degree * Math.PI) / 180
const ans = Math.sin(radians)
console.log(ans)
_.orderBy()
메소드const data = [{
name : 'red queen',
price : 11,
publisher : '한승연'
}, {
name : 'glass sword ',
price : 3,
publisher : '한승연'
}, {
name : 'kings cage',
price : 6,
publisher : '한승연'
}, {
name : 'cruel crown',
price : 24243,
publisher : '한승연'
}]
//_.orderBy 메소드 사용하기
const output = _.orderBy(data, (data) => data.name)
console.log(output)
객체 내부에 어떤 속성이 있는지 확인해보는 것
how? 객체에 없는 속성에 접근하면 undefined
자료형이 나옴 → 조건문으로 undefined
확인
//속성 존재 여부 확인하기
//객체 생성
const obj = {
name : '승연존예',
price : 495737598234792842,
publisher : '한승연'
}
//객체 내부에 속성 있는지 확인
if (obj.name !== undefined){
console.log('속성 존재')
} else {
console.log('속성 없음')
} //존재
if (obj.author !== undefined){
console.log('속성 존재')
} else {
console.log('속성 없음')
} //없음
//기본 속성 지정하기
//객체 생성
const obj = {
name : '승연존예',
price : 495737598234792842,
publisher : '한승연'
}
//객체 기본 속성 지정
obj.name = obj.name !== undefined ? obj.name : '제목 미정' //name이 정의 되어있다면 obj.name 유지, 정의 X면 '제목 미정'으로 설정
obj.author = obj.author !== undefined ? obj.author : '저자 미상'
//객체 출력
console.log(JSON.stringify(obj, null, 2))
배열과 비슷한 방식으로 한 번에 여러 개의 변수에 값을 할당하는 다중 할당 기능이 추가됨
[식별자 , 식별자, 식별자, …] = 배열
let [a,b] = [1,2] //a = 1, b = 2가 할당
console.log(a,b) //1,2
[a,b] = [b,a] //값 교환
console.log(a,b) //2,1
배열의 크기는 같을 필요 없다 (잘림)
{ 속성 이름, 속성 이름 } = 객체
{ 속성 이름 , 속성 이름 } = 객체
{ 식별자 = 속성 이름, 식별자 = 속성 이름 } = 객체
//객체 내부의 name 속성과 price 속성을 꺼내서 변수에 할당하는 코드
//객체 생성
const obj = {
name : '승연존예',
price : 737598234792842,
publisher : '한승연'
}
//객체에서 변수 추출
const { name, price} = obj //name과 price 속성을 그대로 꺼냄
console.log('속성 이름 꺼내서 그대로 출력하기 ')
console.log(name, price)
console.log()
const { a = name, b = price} = obj //name 속성을 a로, price 속성을 b로 꺼냄
console.log('다른 이름으로 속성 꺼내서 출력하기')
console.log(a,b)
//필요한 것 목록
const 필요_1 = ['돈', '잘생긴 남친']
**const 필요_2 = 필요_1**
필요_2.push('김민주님의 시력')
필요_2.push('비오가 읽는 책')
//출력
console.log(필요_1)
console.log(필요_2)
[…배열]
//필요한 것 목록
const 필요_1 = ['돈', '잘생긴 남친']
**const 필요_2 = [...필요_1] //깊은 복사**
필요_2.push('김민주님의 시력')
필요_2.push('비오가 읽는 책')
//출력
console.log(필요_1) //돈, 잘생긴 남친
console.log(필요_2) //돈, 잘생긴 남친, 김민주님의 시력, 비오가 읽는 책
복사한 뒤에 자료를 추가할 경우
[…배열, 자료, 자료, 자료]
//필요한 것 목록
const 필요_1 = ['돈', '잘생긴 남친']
**const 필요_2 = ['비오가 읽는 책', ...필요_1, '김민주님의 시력']** //깊은 복사 + 자료 추가
//출력
console.log(필요_1) //돈, 잘생긴 남친
console.log(필요_2) //비오가 읽는 책, 돈, 잘생긴 남친, 김민주님의 시력
{…객체}
//얇은 복사로 객체 복사하기
const birkin = {
이름 : 'birkin',
나이 : 25,
종족 : 'Hermes'
}
const kelly = {...birkin}
kelly.나이 = 'kelly'
kelly.나이 = 15
console.log(JSON.stringify(birkin))
console.log(JSON.stringify(kelly))
//얇은 복사로 객체 복사하기
const birkin = {
이름 : 'birkin',
나이 : 25,
종족 : 'Hermes'
}
const kelly = birkin
kelly.나이 = 'kelly'
kelly.나이 = 15
console.log(JSON.stringify(birkin))
console.log(JSON.stringify(kelly))
복사한 뒤에 자료를 추가할 경우
{…객체, 자료, 자료, 자료}
//변경하고 싶은 속성만 추가하기
const birkin = {
이름 : 'birkin',
나이 : 25,
종족 : 'Hermes'
}
const kelly = {
...birkin,
이름 : 'kelly', //기존 속성 덮어쓰기
나이 : 15, //기존 속성 덮어쓰기
가격 : '졸라 비쌈'
}
console.log(JSON.stringify(birkin))
console.log(JSON.stringify(kelly))
객체는 전개 순서가 중요함!!
//변경하고 싶은 속성만 추가하기
const birkin = {
이름 : 'birkin',
나이 : 25,
종족 : 'Hermes'
}
const kelly = {
이름 : 'kelly',
나이 : 15,
가격 : '졸라 비쌈',
...birkin //전부 덮어씀
}
console.log(JSON.stringify(birkin))
console.log(JSON.stringify(kelly))