객체
- 객체는 프로그램에서 인식할 수 있는 모든 대상을 가리킴
- 자바스크립트는 모든 것이 객체이다.
객체의 종류
- 문서 객체 모델(DOM) - 웹 문서 자체도 객체이며, 이미지, 링크, 텍스트 필드 모드 객체로 인식
- 브라우저 관련 객체 - 브라우저 정보를 담고 있는 navigator객체를 비롯해 history, location, 스크린 등이 있습니다.
- 내장 객체 - 날짜, 시간, 배열과 같은 프로그래밍 시 자주 사용하는 요소는 미리 객체로 지정되어 있음.
사용법
- 객체를 사용하기 위해서는 인스턴스의 형태로 참조하여 new 예약어를 사용하여 인스턴스 생성 Ex) Date();
// 기본형
new 객체명
// 응용형
var A = new 객체명 ;
// 예시
document.write("현재 시각 : " + A.toLocaleString());
프로퍼티와 메서드 이해하기
- 프로퍼티 - 객체의 특징 및 속성을 의미
- 메서드 - 객체에서 수행할 수 있는 동작을 의미함
자바스크립트의 내장 객체
1. Array 객체
0) 배열 선언 방법
var arrNumber = new Array(); //배열선언
var arrNumber = new Array("a","b","c","d");
var arrNumber = [1,2,3,4];
1) 여러 가지 내장 객체 중에서 배열을 다룹니다.
// 예시
var numbers = new Array(); 배열의 크기 미지정
var numbers = new Array(n); 배열 크기 n 만큼 지정
// 예시 2
var numbers = ["one", "two", "three", "four"]; // 배열 선언
var numbers = Array("one", "two", "three", four); // Array 객체를 사용한 배열 선언
// 예시 3
// length 라는 메소드를 사용하여 배열의 갯수만큼 불러옴 이경우 넘버.랭스는 4이다.
for(i=0; i<numbers.length; i++) {
document.write("<p>" + numbers[i] + "<p>");
}
2) Array 객체의 메서드 종류
- concat : 기본 배열에 요소를 추가해 새로운 배열을 만듭니다.
배열이 아닌 문자열에 concat을 할 경우 구분자 없이 합쳐짐 (예시참고) < 배열이 아닌 경우임
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
let abc = "yy";
console.log(abc.concat("aa","bb"));
// expected output: yyaabb
- every : 모든 요소가 주어진 함수에 대해 참이면 true를 반환하고 그렇지 않으면 false를 반환
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
- filter : 배열 요소중에 주어진 필터링 함수에 true 인 함수만 골라 새로운 배열을 만듦.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
- forEach : 배열의 모든 요소에 대해 주어진 함수를 실행합니다.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
- indexOf : (인덱스 오브) 주어진 값과 일치하는 값이 있는 배열 요소의 첫 인덱스를 찾습니다.
만약 두번째 인수에 n를 입력할 경우 n번째 그 값을 찾습니다. 값이 없을 경우 -1반환
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
- join : 배열 요소를 문자열로 합칩니다. (구분자를 설정하는 것이 중요함)
arr.join([separator])
- push : 배열 끝에 새로운 요소를 추가하고 새로운 length(길이 값)를 반환합니다.
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
- unshift : 배열의 시작 부분에 새로운 요소를 추가합니다. 그리고 length길이값를 반환합니다.
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
- pop : 배열의 마지막 요소를 꺼내고(배열에서 사라짐) 그 값을 결과로 반환합니다.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
- shift : 배열에서 첫번째 요소를 꺼내고(배열에서 사라짐) 그 값을 결과로 반환합니다.
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
- splice : 배열의 요소를 추가하거나 삭제합니다. 반환값은 삭제된 요소.
인수가 1개인 경우 , 0 인덱스 기준 지정된 인수 숫자부터 삭제
인수가 2개일 경우, 지정된 인수 숫자부터 몇개 삭제
인수가 3개일 경우, 삭제 후 추가할 인수 지정
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
- slice : 배열에서 특정한 부분만 잘라냅니다. 원본 배열은 바꾸지 않습니다.
매개변수 arr.splice(a) : 0 인덱스 기준 a부터 끝까지 배열 출력
매개변수 arr.splice(a,b) : 0 인덱스 기준 a부터 0인덱스 b 전 까지 반환
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
- reserve : 배열의 배치 순서를 역순으로 바꿉니다.
let array1 = ['aaa', 'bbb', 'ccc' , 'ddd' , 'eee'];
document.write(array1.reverse());
// expected output : eee,ddd,ccc,bbb,aaa
- sort : 배열요소를 지정한 조건에 따라 정렬합니다. 숫자 순, 혹은 알파벳 순
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
- toString : 배열에서 지정한 부분을 문자열로 반환합니다.
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"
2. Date 객체 (날짜와 시간 정보를 나타냄)
- 날짜를 사용하려면 Date 객체를 사용. 인스턴스를 참조하여 new Date(); 와 같은 형태로 불러옴.
1) Date 객체를 통해 특정 날짜 및 시간 나타내기
new Date(); // 현재 시간 및 날짜 표현
new Date("2021-10-05"); // 특정 날짜 가져오기
new Date("2020");
new Date("MM/DD/YYYY");
new Date("2021-12-12T17:00:00"); // 특정 날짜 및 시간 가져오기
new Date("Mon Jan 20 2020 15:00:00 GMT+0900 (대한민국 표준시)");
2) Date 객체의 메서드
- getFullyear, getMonth, getDatem, getDay, getTime, getHours, getMinutes, getSeconds, getMilliseconds 등
- 앞에 get 대신 set을 붙이면 얻는 것이 아니라 인수 안의 값을 세팅함
- toLocaleString() 을 사용하면 날짜와 시간을 현지에 맞추어 표기
- toString() 를 사용하면 Date 타입 객체를 문자열로 표현함.
// 어떤 날짜로 부터 현재까지 구하기
let readFrom = new Date("2021-11-27");
let now = new Date();
let nowtime = now.getTime();
let readtime = readFrom.getTime();
let duringTime = nowtime - readtime;
duringTime = Math.round(duringTime/1000/60/60/24);
document.querySelector('.accent').innerText = duringTime
- 응용 해보기 ) 입력받은 날짜를 바탕으로 일수 출력 - 잘작동함
let now = new Date(); // 현재시간 불러옴
let yearUser = prompt("시작년도 ex) YYYY"); // 시작 년월일 받기(유저로부터)
let monthUser = prompt("월수 ex) MM");
let dayUser = prompt("일수 ex) DD");
var readFrom = new Date(yearUser + "-" + monthUser + "-" + dayUser); // 날짜 선언
let nowtime = now.getTime(); // 날짜 밀리초 계산 및 인수 환원
let readtime = readFrom.getTime();
let duringTime = nowtime - readtime;
duringTime = Math.round(duringTime/1000/60/60/24);
document.querySelector('.accent').innerText = duringTime
3. Math 객체
- math는 수학관련 메서드를 사용한다. math 객체는 따로 인스턴스를 만들어서 사용하진 않는다.
//사용 방법
Math.프로퍼티명
Math.메서드명
1) Math 객체의 프로퍼티
- E : 오일러 상수
- PI : 원주율
- SQRT2 : 루트 2 , SQRT1_2 : 1/루트2
- LN2 : log e 2 의 값, LN10 : log e 10 의 값 ( 여기서 e 는 아래 첨자를 의미한다)
- LOG2E : log 2 e 의 값, LOG10E : log 10 e ( 여기서 숫자는 아랫 첨자를 의미한다)
2) Math 객체의 메서드 - 모질라 사이트가면 자세히 알수있음
- abs 절대값, sqrt 제곱근 반환, min 최소값, max 최대값(배열을 인수로 집어넣으면 반응안함)
- acos, asin, atan 아크코사인, 아크사인, 아크탄젠트 반환
- cos, sin, tan 코사인 사인 탄젠트 값 반환
- exp 지수함수, log 로그 함수, round 소수점 이하 반올림, floor 소수점 이하 버림, ceil 소수점 이하 올림
- pow - 매개 변수의 지숫값을 반환함
- random - 0과 1사이의 무작위 수를 반환함
3) 랜덤함수를 통한 숫자 뽑기
let manNum = parseInt(prompt("사람수"));
console.log(Math.floor(Math.random() * manNum+1));
브라우저와 관련된 객체
- 내장 객체 : window, document, navigatior, history, location, screen 등이 존재함
1.window 객체
1) 프로퍼티, 메서드( open("경로", "창이름", "창옵션"), close() 와 같은 메서드 )
2) 창을 새로 열때마다 생기는 객체. 모든 객체의 상위에 존재한다
2.navigator 객체
1) 웹브라우저의버전부터플러그인 설치정보 및 온, 오프라인정보를 포함 (수정 불가)
2) userAgent 프로퍼티 유저의 윈도우, 브라우저, 모질라 버전등을 표기합니다.
3.history 객체
1) 뒤로 앞으로 등 주소 표시줄에 입력해서 방문사이트가 배열로 표기됨 (읽기 전용)
2) length 프로퍼티 : 지금까지 방문한 사이트 표기
3) back,forward,go 메서드 : 뒷 페이지, 앞페이지, 혹은 정해진 숫자만큼 페이지를 이동
4. location 객체
1) 브라우저의 주소 표시줄과 관련됩니다. 즉 location 객체에는 현재 문서의 URL 주소 정보가 들어있음
따라서, 이정보를 편집하면33 현재 브라우저 창에 열어야 할 사이트나 문서를 지정할 수 있습니다.
2) reload() 메서드 : 새로고침과 같은 역할을 함 / replace() 메서드 : 현재 창에 다른 문서나 사이트를 보여줌
document.write("<p><b>location.href : </b>" + location.href + "</p>"); // 현재주소
document.write("<p><b>location.host : </b>" + location.host + "</p>"); // 현재 ip
document.write("<p><b>location.protocol : </b>" + location.protocol + "</p>");// 현재 프로토콜
<button onclick="location.replace('http://www.easyspub.com')">홈페이지로 이동</button>
// 현재 브라우저의 탐색 현황을 기재된 페이지 하나로 만듭니다.
<button onclick="javascript:location.replace('http://www.easyspub.com')">홈페이지로 이동</button>
// 위와같이 표현하여도 문제없음
- 예제 풀기 2022/01/03
'WEB > JAVASCRIPT' 카테고리의 다른 글
| [JAVASCRIPT] 함수의 기본 (0) | 2021.12.08 |
|---|---|
| [JAVASCRIPT] 기본 지식 & 명령어 (continue문 까지) (0) | 2021.12.06 |
| [JAVASCRIPT] 기초 (0) | 2021.11.29 |
댓글