[자바 스크립트] Date 객체, Array 객체

남한탐정김정은·2023년 2월 6일
0

자바스크립트

목록 보기
30/32
post-thumbnail

Date 객체

클래스설명
new Date()현재시간으로 Date 객체를 생성
new Date(유닉스_타임)유닉스 타임(1970년 1월 1일 00시 00분 00초부터 경과한 ms)으로 Date객체를 생성
new Date(시간_문자열)문자열로 Date 객체를 생성
new Date(연,월-1,일,시,분,초.밀리초)시간요소를 기반으로 Date객체를 생성

메소드 활용
Date 객체는 특정 시간 요소를 가져오는 메소드를 사용할 수 있다.

메소드설명
getFullyear0000년도를 리턴
getMont00월을 리턴
getDay00일을 리턴
getHours00시를 리턴
getMinutes00분을 리턴
getSeconds00초를 리턴

Array 객체

메소드설명
concat()매개 변수로 입력한 배열의 요소를 모두 합쳐 배열을 만들어 리턴
join()배열 안의 모든 요소를 문자열로 만들어 리턴
pop()배열의 마지막 요소를 pop하고 리턴
push()배열의 마지막에 새로운 요소를 추가(push)
reverse()배열의 요소 순서를 뒤집는다.
slice()배열 요소의 지정한 부분을 리턴
sort()배열의 요소를 정렬
splice()배열 요소의 지정한 부분을 삭제하고 삭제한 요소를 리턴

배열의 push, pop

let arr = [{
    name: '고구마',
    price: 1000
},{
    name: '감자',
    price: 500
},{
    name: '바나나',
    price: 1500
}];

let popped = arr.pop();
console.log('-배열에서 꺼낸 요소');
console.log(popped);
console.log('-pop() 메소드를 호출한 이후의 배열');
console.log(arr);

arr.push(popped); //바나나 다시 넣기
arr.push({
    name: '사과',
    price: 2000
});
console.log('push 두번 이후의 배열');
console.log(arr);

실행 결과

-배열에서 꺼낸 요소
{ name: '바나나', price: 1500 }
-pop() 메소드를 호출한 이후의 배열
[ { name: '고구마', price: 1000 }, { name: '감자', price: 500 } ]
push 두번 이후의 배열
[
{ name: '고구마', price: 1000 },
{ name: '감자', price: 500 },
{ name: '바나나', price: 1500 },
{ name: '사과', price: 2000 }
]


배열의 sort
sort()는 단순한 배열일 때는 그냥 사용하지만 객체 내부의 특정 값으로 정렬하고 싶을 때는 매개변수에 함수를 넣고, 대소를 비교 -1(앞의 것이 작다), 0(같다), 1(앞의 것이 크다)을 리턴한다.

let arrA = ['고구마', '감자','바나나']
let arrB = [{
    name:'고구마',
    price:1000
},{
    name:'감자',
    price:500
},
{
    name:'바나나',
    price:400
}];

arrA.sort();
console.log('문자열 정렬')
console.log(arrA) //[ '감자', '고구마', '바나나' ]
console.log();
console.log('문자열 정렬(역순)')
console.log(arrA.reverse()) //[ '바나나', '고구마', '감자' ]
console.log();

arrB.sort((itemA, itemB)=>{
    return itemA.price - itemB.price //숫자가 작은 순으로 정렬
})
console.log('객체 내부의 숫자로 정렬')
console.log(arrB)
console.log()

arrB.sort((itemA,itemB)=>{
    if (itemA.name < itemB.name){
        return -1;
    }
    else if(itemA.name > itemB.name){
        return 1;
    }
    else{
        return 0;
    }
})
console.log('객체 내부의 문자열로 정렬')
console.log(arrB)

실행 결과

문자열 정렬
[ '감자', '고구마', '바나나' ]

문자열 정렬(역순)
[ '바나나', '고구마', '감자' ]

객체 내부의 숫자로 정렬
[
{ name: '바나나', price: 400 },
{ name: '감자', price: 500 },
{ name: '고구마', price: 1000 }
]

객체 내부의 문자열로 정렬
[
{ name: '감자', price: 500 },
{ name: '고구마', price: 1000 },
{ name: '바나나', price: 400 }
]

profile
남한에 놀러온 김..

0개의 댓글