{}를 이용해서 객체의 데이터를 묶는다.{ 속성: 값, '속성': 값 }
객체.속성객체['속성'] : 속성이 문자열로 사용될 때 대괄호[] 표기법을 사용한다.
- 객체 만들기
<script> var person = { name: '홍길동', age: 30, isAlive: true, hobbies: [ '여행', '운동', '요리' ], bef: { // 객체 안에 객체를 가질 수 있다. name: '고길동', age: 30 }, info: function(){ // 객체 안에 함수도 가질 수 있다. console.log('이름: ' + this.name + ', 나이: ' + this.age); // 현재 객체(person === this) } } </script>
- 객체 속성 확인
<script> console.log('name: ' + person.name); console.log('age:' + person.age); console.log('isAlive:' + person.isAlive); for(let i = 0; i < person.hobbies.length; i++){ console.log('hobbies:' + person.hobbies[i]); } console.log("bef's name:" + person.bef.name); console.log("bef's age:" + person.bef.age); (person.info)(); </script>
- 빈 객체 생성
var car = {};
- 속성 추가
car.model = '모닝'; car.maker = 'kia';
- 속성 수정
car.model = '레이';
- 속성 삭제
delete car.maker;
new 키워드를 이용해서 객체를 만들 수 있다.function 함수명(매개변수, 매개변수, ...){ this.속성 = 매개변수; this.속성 = 매개변수; ... }
- 생성자 함수 정의
function Product(code, name, price){ this.code = code; this.name = name; this.price = price; }
- 생성자 함수 호출(객체 생성)
var product = new Product('A123', '청소기', 10000);
- 객체 속성 확인
console.log(product['code']); console.log(product['name']); console.log(product['price']);
- 객체 생성
var book = { title: '어린왕자', author: '생택쥐베리', price: 10000 };
- 객체 속성 순회
for(let p in book){ // 객체 book의 속성(property)들이 변수 p로 하나씩 전달된다. // 이 때 변수 p의 타입은 string 이므로, book.p는 동작하지 않고 book[p]만 동작한다. console.log(book.p); // 안 됨 console.log(book[p]); // 됨 }
JavaScript 객체 -> 문자열 형식의 JSON 데이터
var 문자열 = JSON.stringify(객체)
문자열 형식의 JSON 데이터 -> JavaScript 객체
var 객체 = JSON.parse(문자열)
- 객체 생성
var person = { name: '홍길동', age: 30 };
- 객체 -> 문자열
var str = JSON.stringify(person); console.log(typeof str, str);
- 문자열 -> 객체
var person = JSON.parse(str); console.log(typeof person, person);
getTime() getFullYear() getMonth() getDate() getHours() getMinutes() getSeconds()// 타임스탬프 var timestamp = Date.now(); console.log(timestamp); // 문자열 형식의 현재 날짜와 시간 var strNow = Date(); // new Data().toString() console.log(typeof strNow, strNow); // 객체 형식의 현재 날짜와 시간 var now = new Date(); console.log(typeof now, now); // 년,월,일,시,분,초,타임스탬프 var year = now.getFullYear(); var month = now.getMonth(); // 주의! 0 ~ 11 var day = now.getDate(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); var timestamp = now.getTime(); console.log(year, month, day, hour, minute, second, timestamp); // 특정 날짜와 시간을 가진 객체 생성 var someday = new Date(2023, 8, 30, 16, 30, 30); // 2023-09-30 16:30:30 (8월이 아님 주의!) console.log(someday);
- Sctring 문자열 표현 방식
'' "" `${}`
- 문자열의 길이
.length
- 특정 문자(지정된 인덱스에 위치하는 문자)
.charAt(0): 첫번째 문자.length - 1: 마지막 문자
- 특정 문자열
substringsubstrslice: -인덱스를 지원한다.
- 특정 패턴으로 시작 / 특정 패턴으로 끝나는지 검사
.startsWith.endsWith
- 특정 문자열의 위치(인덱스) 찾기
.indexOf: 첫번째 인덱스를 반환.lastIndexOf: 마지막 인덱스를 반환
- 특정 문자열을 주어진 길이만큼 채우기
padEndpadStart
- 주어진 횟수만큼 반복하기
repeat
- 찾아 바꾸기
replace: 하나만 바꿈replaceAll: 모두 바꿈
- 대소문자 변환하기
toLowerCase(): 모두 소문자로 변환toUpperCase(): 모두 대문자로 변환
- 문자열 앞뒤로 포함된 불필요한 공백 제거하기 (중간 X)
trim()trimStart(): alias 가능 →trimLeft()trimEnd(): alias 가능 →trimRight()
- 문자열 객체의 문자열 값 반환
valueOf()var str = new String('JavaScript');
console.log(str);: 객체 {'JavaScript'} 출력console.log(str.valueOf());: 문자열 'JavaScript' 출력
- 문자열을 분리해서 배열로 만들기
split(' ')var str = 'Hello tom Nice to meet you!';
var words = str.split(' ');
words = ['Hello', 'tom', 'Nice', 'to', 'meet', 'you!']console.log(words[1]);: 배열로 만든 요소 확인해보기
'tom'
반복 메소드 forEach
- for문 돌리기의 메소드 버전 (배열에 있는 요소를 하나씩 꺼내기)
- 콜백함수로 되어있다.
필터 array.filter
array.filter((요소) => 요소 검사);- 지정한 조건을 만족하는 요소만 남긴 배열 만들기
배열 요소를 변경하기 array.map
array.map((요소) => 변경할 값)
배열 요소를 합쳐서 문자열로 반환하기 array.join
array.join(): 콤마(,)로 연결 (디폴트)array.join(' '): 공백으로 연결
- 절대값
Math.abs()
- 정수 올림값
Math.ceil()
- 정수 내림값
Math.floor()
- 정수 반올림
Math.round()
- 소수점 절사
Math.trunc()
- 주어진 값 중 가장 큰 수
Math.max()- 주어진 값 중 가장 작은 값
Math.min()
- 배열의 요소 중 가장 큰 값
- (배열은 전개연산자 형식으로 전달하면 알아서 풀려서 전달됨)
Math.max(...array)- 배열의 요소 중 가장 작은 값
Math.min(...array)
- 제곱
Math.pow()
Math.pow(2, 3): 8, 2의 3제곱
- 난수 random
Math.random()
- 루트
Math.sqrt()
Math.sqrt(25): 5, 루트 25
👉Built-in Object 활용 예제 깃허브(클릭)

히히~!