티스토리 뷰
728x90
반응형
객체
- 객체와 프로피터
- 객체 : 중괄호로 생성 | 쉼표로 구분
- 프로피터 : 중괄호 안에 있는 속성
- name 주의사항 : 첫번째 글자는 반드시 문자, 밑줄, 달러 중 하나로 시작 | 띄어쓰기&하이픈 금지 → 규칙을 벗어난다면 반드시 따옴표로 감싸줘야 함
- value는 모든 자료형 가능 | value 안에 객체 생성 가능
- 객체에서 데이터 접근하기
- 존재하지 않는 값은 undefined
// 객체 생성
let study = {
name: '메롱',
'born Year': 2017,
isVeryNice: true,
worstCourse: null,
bestCourse: {
title: '자바스크립트 프로그래밍 기초',
language: 'JS'
}
};
// 점 표기법 (objectName.propertyNmae)
console.log(study.name);
// 대괄호 표기법 (objectName['propertyNmae'])
console.log(study['born Year']);
console.log(study['born' + ' Year']);
// 변수로 전달
let propertyName = 'name';
console.log(study[propertyName]);
// 객체 내 객체로 접근
console.log(study.bestCourse.title);
console.log(study.bestCourse.['title']);
- 객체 다루기
let study = {
name: '메롱',
'born Year': 2017,
isVeryNice: true,
worstCourse: null,
bestCourse: {
title: '자바스크립트 프로그래밍 기초',
language: 'JS'
}
};
// 객체 변경
study.name = 'hi';
// 객체 추가
study.ceo = '홍길동';
// 객체 삭제
delete study.worstCourse;
// 객체 프로퍼티 여부 확인
console.log(study.name !== undefined);
// 'propertyName' in object
console.log('name' in study);
- 객체와 메소드
- 메소드 : 연관성 있는 여러 함수들을 하나로 묶는 것
// 메소드
let greetings = {
sayHello: function() {
console.log('Hello!');
},
sayHello2: function(name) {
console.log(`Hello ${name}!`);
},
sayHi: function() {
console.log('Hi!');
},
sayBye: function() {
console.log('Bye!');
}
};
// 점 표기법
greetings.sayHello();
// 파라미터가 필요한 경우
greetings.sayHello2('durian');
// 대괄호 표기법
greetings['sayHello2']('durian');
- for... in 반복문
- 객체는 정수형 프로퍼티 네임을 오름차순으로 먼저 정렬하고, 나머지 프로퍼티들은 추가한 순서대로 정렬하는 특징이 있음
for(변수 in 객체) {
동작부분
}
for(let key in codeit) {
console.log(key);
console.log(codeit.[k]);
}
- Date 객체(날짜객체)
- 내장객체 : 자바스크립트가 미리 가지고 있는 객체
- Date : 일자
- Day : 요일 [일(0)~토(6)]
// Date
let myDate = new Date();
console.log(myDate);
>> 객체 생성한 순간 시간 출력
// Date(milliseconds)
let myDate = new Date(1000);
>> 1970년 1월 1일 0시0분0초 UTC + 1000밀리초
// Date ('YYYY-MM-DD')
let myDate = new Date('2024-11-06');
// Date ('YYYY-MM-DDThh:mm:ss')
let myDate = new Date('2024-11-06T01:55:24');
// Date(YYYY, MM, DD, hh, mm, ss)
// month는 0부터 시작(4 입력 -> 5월 출력)
let myDate = new Date(2014, 4, 18, 19, 11, 16);
// Date.getTime() : 1970.1.1 00:00:00 부터 몇 밀리초가 지났는지
let myDate = new Date(2017, 4, 18, 19, 11, 16);
console.log(myDate.getTime());
console.log(myDate.getFullYear());
console.log(myDate.getMonth());
console.log(myDate.getDate());
console.log(myDate.getDay());
console.log(myDate.getHours());
console.log(myDate.getMinutes());
console.log(myDate.getSeconds());
console.log(myDate.getMilliseconds());
- 두 날짜 사이 차 구하기
- 타임스탬프 단위는 밀리초이기 때문에, 일수로 바꿔야 함
- 1000밀리초 = 1초 | 60초 = 1분 | 60분 = 1시간 | 24시간
- dayDiff는 두 날짜간 차이 값이기에, 며칠째인지 계산하려면 당일 날짜를 더해야 함.
- 타임스탬프 단위는 밀리초이기 때문에, 일수로 바꿔야 함
let today = new Date(2112, 7, 24);
let jaeSangStart = new Date(2109, 6, 1);
function workDayCalc(startDate) {
let timeDiff = today.getTime() - startDate.getTime();
let dayDiff = timeDiff / 1000 / 60 / 60 / 24;
console.log(`오늘은 입사한 지 ${dayDiff + 1}일째 되는 날 입니다.`);
}
workDayCalc(jaeSangStart);
배열
- 배열 : 대괄호로 생성 | 배열도 객체
let courseRanking = [
'JS 프로그래밍 기초',
'git으로 배우는 버전 관리',
'컴퓨터 개론',
'파이썬 프로그래밍 기초'
];
// indexing (0~...)
console.log(courseRanking [0]);
>> JS 프로그래밍 기초
- 배열 다루기
let members = ['메롱', '안녕', '핸드폰', '토끼', '고양이'];
// 객체 개수 확인
console.log(members.length); // 5
console.log(members['length']); // 5
console.log(members[members.length - 1]); // 고양이
// 배열 요소 추가 및 수정
members[5] = '나이스';
console.log(members[5]); // 나이스
// 배열 요소 삭제
delete members[4]; // empty로 출력(방만 뺀 느낌... 완전히 삭제X)
- 배열 메소드
// splice(시작인덱스, 삭제할요소개수, item) : 배열 요소 완전히 삭제
// 4 이후 요소 다 삭제
members.splice(4);
// 1번 인덱스부터 요소 2개 삭제
members.splice(1, 2);
// 1번 인덱스부터 요소 1개 삭제 후 '나이스', '하이' 요소 추가
members.splice(1, 1, '나이스', '하이');
// splice로 요소 추가
members.splice(1, 0, '나이스', '하이');
// 배열 첫 요소로 값 추가
members.splice(0, 0, '나이스');
// 배열 마지막 요소로 값 추가
members.splice(members.length, 0 '하이');
// 마지막 요소 삭제
members.splice(members.length - 1, 1);
// 배열의 첫 요소 삭제 : shift()
members.shift()
// 배열의 마지막 요소 삭제 : pop()
members.pop();
// 배열의 첫 요소로 값 추가 : unshift(value)
members.unshift('나이스');
// 배열의 마지막 요소로 값 추가 : push(value)
members.push('하이');
- 배열의 특정값 찾기 : 포함되어 있지 않다면 -1 리턴
let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];
// indexOf(value) : 앞에서 부터 탐색
console.log(brands.indexOf('Kakao')); // 1
console.log(brands.indexOf('Daum')); // -1
// lastIndexOf(value) : 뒤에서 부터 탐색
console.log(brands.lastIndexOf('Kakao')); // 3
console.log(brands.lastIndexOf('Daum')); // -1
// 특정 값이 있는지 확인
console.log(brands.includes('Kakao')); // true
console.log(brands.includes('Daum')); // false
- 배열 뒤집기
let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];
console.log(brands);
brands.reverse();
console.log(brands);
>> (4) ["Google", "Kakao", "Naver", "Kakao"]
>> (4) ["Kakao", "Naver", "Kakao", "Google"]
- for...of 반복문
- for..in문은 일반적인 객체에 최적화... 따라서 배열엔 for..of문 권장
for(변수 of 배열) {
동작부분;
}
for (let i of influencer) {
console.log(i);
}
- 다차원 배열
let twoDimensional = [[1,2],[3,4]];
console.log(twoDimensional[0][1]);
728x90
반응형
'JavaScript' 카테고리의 다른 글
[JS기초] 객체 지향 프로그래밍 (1) | 2024.11.11 |
---|---|
[JS기초] 객체와 클래스 (0) | 2024.11.10 |
[JS기초] 자료형 심화 (0) | 2024.11.08 |
[JS기초] 제어문(조건문, 반복문) (2) | 2024.11.07 |
[JS기초] 프로그래밍 기초 | 자료형 | 추상화 (3) | 2024.11.07 |