Language/JavaScript
[JavaScript] 객체
병훈1234
2021. 7. 25. 19:04
객체
- 블록 내에 property name : property value (key : value)
- property name
- 따옴표 생략 가능
- 첫글자 문자, 밑줄, 달러, 띄어쓰기 금지, 하이픈(-) 금지
- 정 써주어야 한다면 따옴표로 표기하면 된다
- property value
- 모든 자료형 가능, 객체도 들어갈 수 있음
- 각각의 키와 값은 ,(콤마)로 구분
let object = { Name: 'Lee', Year: 2021, MyStatus: true, currentCourse: null, bestCourse: { title: '자바스크립트', language: 'javascript' }, "is happy": true } console.log(object)
접근법
- 객체명.프로퍼티명으로 접근
- 단, 띄어쓰기나 숫자로 시작하는 프로퍼티명 불가능
- 객체명["프로퍼티명"] 으로 접근
- 위에서 안되는 띄어쓰기, 숫자 시작 가능
- 만약 존재하지 않는 프로퍼티명을 접근한다면?
- null 반환
console.log(object.Name)
console.log(object["is happy"])
property 추가/변경/삭제
- 객체의 property 값 수정
- 객체의 프로퍼티에 접근 후 값을 대입해주면 된다.
object.Name = 'Kim'; // Name은 이미 있는 property console.log(object.Name);
- 객체의 property 값 추가
- 그냥 있는것처럼 접근 후 값 대입해주면 된다.
object.job = 'soldier'; console.log(object.job);
- 객체의 property 값 제거
- delete 객체.프로퍼티명
console.log(object.job) // job 값 출력 delete object.job console.log(object.job) // undefined
객체 내부 property 존재여부 확인
- '프로퍼티명' in 객체
- 직접적으로 undefined 비교할수도 있지만 초기에 undefined 할당할수도 있기 때문에 in이 나음.
if ("is happy" in object) { console.log("있어요."); } else { console.log("없어요."); }
객체 내부 메소드 생성
- 프로퍼티 만들듯이 하면 된다.
let calculator = { add: function(a, b) { return a + b; }, minus: function(a, b) { return a - b; }, multiply: function(a, b) { return a * b; } } console.log(calculator.add(3, 5));
for .. in 반복문
- 객체의 프로퍼티 이름들을 반복
- 객체의 key값들을 하나씩 가져옴.
- 프로퍼티 이름이 숫자인 경우 오름차순 정렬, 나머지 프로퍼티명들은 추가한 순서대로
for (변수 in 객체) {
동작부분
}
for (let key in object) {
/* 키/값 출력 */
console.log(key)
console.log(object[key])
}
Date 객체
let mydate = new Date();
let mydate = new Date(1000); // 1970년 기준 1000밀리초 지남
let mydate = new Date("2021-07-24")
let mydate = new Date("2021-07-24T19:06:00")
let mydate = new Date(YYYY, MM, DD, HH, mm, ss, ms); // Month는 0부터 시작!!
mydate.getTime() //-> 1970/1/1 00:00:00부터 몇 밀리초 지났는지 => Time Stamp
mydate.getDate() //-> 일자
mydate.getDay() //-> 요일
/* 날짜 차이 구할수 있음 */
let myDate1 = new Date(2017, 4, 18);
let myDate2 = new Date(2017, 4, 19);
/* 날짜에 정수 연산 가능 */
let timeDiff = myDate2 - myDate1;
console.log(timeDiff); // 86400000 (ms)
console.log(timeDiff / 1000); // 86400 (sec)
console.log(timeDiff / 1000 / 60) // 1440 (min)
console.log(timeDiff / 1000 / 60 / 60) // 24 (hour)
console.log(timeDiff / 1000 / 60 / 60 / 24) // 1 (date)