###########################################################################
###########################################################################
6장. 객체 (object) - **********************
###########################################################################
1. 종류 3가지
==> 자바처럼 상속과 비슷한 개념(프로토타입(prototype) 관계)으로 계층구조화 되어 있음.
최상위 객체는 Object 이다.
==> 객체의 구성요소는 변수,메서드(정적메서드, 인스턴스 메서드),생성자를 가짐.
1> 데이터(기본+참조) 관련 객체
-문자관련 ==> String 객체가 관리
-수치 ==> Number 객체가 관리
-날짜 ==> Date 객체가 관리
-배열 ==> Array 객체가 관리 (***************)
Set/Map 같은 컬렉션 제공됨(ES6)
-JSON ==> object 객체가 관리
2> BOM ( Browser Object Model)
- 웹 브라우저 관련 객체
- 종류
Window 객체
Screen 객체
Histroy 객체
Location 객체
Navigator 객체
3> DOM ( Document Object Model )
- html 문서 관련 객체
- Document 객체 ( 자동으로 생성됨. document 변수로 참조 )
2. 데이터 관련 객체
1> 문자데이터 관련 객체
- String 객체 관리
- 생성방법 3가지
가. 리터럴값만 이용 (권장)
let s = "hello";
나. new 생성자 이용
let s2 = new String("hello");
다. 생성자 이용
let s3 = String("hello");
- 문자열 표현방법 3가지
가. 'hello' 이용
나. "hello" 이용
다. `hello` 이용( 백틱, template literal ) (*****************************)
* 백틱장점 2가지
1> 변수삽입 가능: ${변수}이용
2> 들여쓰기, 엔터 같은 동작이 그대로 적용되어 출력포맷의 가독성이 높아진다.
- 메서드 조회
http://developer.mozilla.com
<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련1_String3_메서드</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// 문자열 메서드
// http://developer.mozilla.com
let s = 'HeLlo';
console.log("1. 문자열 길이: ", s.length);
console.log("2. 특정문자얻기: ", s.charAt(0));
console.log("3. 문자열 연결: ", s.concat("!!!", "###", "%%%%"));
console.log("4. 특정문자 위치얻기: ", s.indexOf('H'));
console.log("5. 부분열: ", s.substring(0, 4)); // 0 ~ 3 까지, substring(start, end)
console.log("5-1. 부분열: ", s.substr(0, 4)); // 0 부터 4개, substr(start, end)
console.log("6. 대문자: ", s.toUpperCase());
console.log("7. 소문자: ", s.toLowerCase());
console.log("8. 치환: ", s.replace('H', 'X'));
console.log("9. 값포함여부: ", s.includes("He"));
console.log("9-1. 값포함여부: ", s.includes("Xe"));
console.log("10. 시작값 여부: ", s.startsWith("He"));
console.log("11. 끝값 여부: ", s.endsWith("o"));
let s2 = " world ";
console.log("12. 공백제거: ", s2.trim()); // 양쪽공백제거
console.log("12-1. 공백제거후 길이: ", s2.trim().length);
let s3 = "홍길동/이순신";
let result = s3.split("/"); // result 가 배열
console.log("13. 구분자: ", result, result[0]); // result[0] 은 홍길동만 추출
let s4 = "홍길동";
console.log("14. 문자열반복: ", s4.repeat(3));
</script>
</head>
<body>
</body>
</html>

2> 수치 데이터 관련 객체
- 정수와 실수를 모두 관리한다.
- Number 객체가 관리한다.
- 생성방법 3가지
가. 리터럴값만 이용 (권장)
let n = 100;
나. new 생성자 이용
let n2 = new Number(100);
다. 생성자 이용
let n3 = Number(100);
<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련2_Number</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// 수치 데이터 생성
let s = 10; // number
let s2 = new Number(10); // object
let s3 = Number(10); // number
console.log(s, s2, s3);
console.log(typeof s, typeof s2, typeof s3);
</script>
</head>
<body>
</body>
</html>

- Number객체 메서드 정리
<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련2_Number2_메서드</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// 수치 데이터 메서드
let n = 10;
console.log("1. 문자열로 변경(10진수): ", n.toString());
console.log("1-1. 문자열로 변경(2진수): ", n.toString(2));
console.log("1-2. 문자열로 변경(8진수): ", n.toString(8));
console.log("1-3. 문자열로 변경(16진수): ", n.toString(16));
let n2 = 3.147743;
console.log("2. 소수점 표현(정수): ", n2.toFixed());
console.log("2-1. 소수점 표현(2째자리): ", n2.toFixed(2));
console.log("2-2. 소수점 표현(5째자리): ", n2.toFixed(5));
console.log("3-1. Number 의 최소값: ", Number.MIN_VALUE);
console.log("3-2. Number 의 최소값: ", Number.MAX_VALUE);
console.log("4-1. NaN 이냐: ", Number.isNaN(0));
console.log("4-2. NaN 이냐: ", Number.isNaN(NaN));
console.log("5-1. 정수냐: ", Number.isInteger(10));
console.log("5-2. 정수냐: ", Number.isInteger(3.14));
// "10" ---> 10 변경
console.log("6. 문자열 -> 숫자: ", Number.parseInt("10"));
</script>
</head>
<body>
</body>
</html>

3> 날짜 데이터 관련 객체
- Date 객체가 관리.
- 생성방법 2가지
let d = new Date();
let d2 = Date();
<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련3_Date</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// 날짜 데이터 생성
let d = new Date(); // obejct
let d2 = Date(); // string
console.log(d, d2);
console.log(typeof d, typeof d2);
</script>
</head>
<body>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련3_Date2_메서드</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// 날짜 데이터 생성
let d = new Date(); // obejct
console.log("1. 년도: ", d.getFullYear());
console.log("2. 월: ", d.getMonth() + 1); // 범위가 0 ~ 11 이라서 +1 을 해줘야한다.
console.log("3. 일: ", d.getDate());
console.log("4. 시간: ", d.getTime());
console.log("5. 분: ", d.getMinutes());
console.log("6. 초: ", d.getSeconds());
console.log("7. 밀리초: ", d.getMilliseconds());
console.log("8. 요일: ", d.getDay()); // 5(2024-05-03기준); 일:0 , 월:1 ,..., 금:5,토:6
// 원하는 날짜 설정
d.setFullYear(2002);
d.setMonth(7);
d.setDate(15);
console.log("9. 설정날짜: ", d);
</script>
</head>
<body>
</body>
</html>

4> 배열 데이터 관련 객체
- Array 객체가 관리
- 특징: 자바의 List 처럼 동작됨.
- 생성방법
var n = [10,20,30];
var n = [];
var n = new Array();
var n = new Array(10,20,30);
var n = Array();
var n = Array(10,20,30);
<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련4_Array</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// 배열 데이터 생성
var n = [10, 20, 30];
console.log(n);
var n = [];
console.log(n);
var n = new Array();
console.log(n);
var n = new Array(10, 20, 30);
console.log(n);
var n = Array();
console.log(n);
var n = Array(10, 20, 30);
console.log(n);
</script>
</head>
<body>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<title>js07_객체1_데이터관련4_Array2_메서드</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// Array 메서드
var n = [10, 20, 30];
// 1. 값 얻기
console.log("1. 개별적인 인덱스 이용; ", n[0], n[1]);
console.log("2. 일반 for 문: ");
for (var i = 0; i < n.length; i++) {
console.log(n[i]);
}
console.log("3. foreach 문 역할: ");
/*
자바
for(int x : arr) {}
JS
for(var x of arr) {}
for(var x in arr) {}
*/
for (var x of n) {
console.log(x);
}
console.log("3-1. foreach 문 (index, n[x])");
for (var x in n) {
console.log(x, n[x]);
}
// 2. 값추가 / 값삽입 / 값삭제 / 값변경
var n2 = [10, 20, 30];
console.log("4.배열 마지막에 값 추가");
// index 로 추가가 가능하지만 push 권장
// n2[3] = 40;
// console.log(n2);
n2.push(40);
n2.push(50, 60, 70);
console.log(n2); // 10 20 30 40 50 60 70
console.log("5. 배열 마지막에 값 삭제");
n2.pop(); // 위에서 추가한 70 삭제
console.log(n2); // 10 20 30 40 50 60
console.log(n2.pop()); // 삭제한 값이 반환 / 60
console.log("6. 배열 중간에 값 삽입 및 삭제");
/*
array.splice(start[,deleteCount[, item1[,item2[, ...]]]])
array.splice(0,3) ==> 0 부터 시작해서 3개 삭제
array.splice(0,3,10,20) ==> 0 부터 시작해서 3개 삭제하고 10 과 20 삽입
sarray.splice(0,0,10,20) ==> 0 부터 10 과 20 삽입
*/
var n3 = [10, 20, 30];
// n3.splice(0, 0, 40, 50, 60); // 0 부터 0개 삭제하고 40,50,60 삽입
// n3.splice(1, 2, 40, 50, 60); // 1 부터 2개 삭제하고 40,50,60 삽입
n3.splice(1, 2); // 1부터 2개 삭제
console.log(n3);
var n4 = [10, 20, 30, 40, 50, 60];
console.log("7. 특정위치값 반환: ", n4.indexOf(20));
// slice(start?: number | undefined, end?: number | undefined): number[]
console.log("8. 부분열: ", n4.slice(0, 4)); // 10 20 30 40
console.log("9. 거꾸로: ", n4.reverse()); // 60 50 40 30 20 10
var n5 = [10, 20, 30, 40, 50, 60];
console.log("10. 특정값으로 채우기: ");
// fill(value), fill(value,start), fill(value,start,end)
// n5.fill(100); // 100 100 100 100 100 100
// n5.fill(100, 3) // 10 20 30 100 100 100
n5.fill(100, 0, 3) // 100 100 100 40 50 60
console.log(n5);
var n6 = [10, 20, 30, 40, 50, 60];
console.log("11. 배열안의 값으로 배열채우기: ");
// copyWithin(targer, start), copyWithin(targer, start, end)
// let new_array = n6.copyWithin(0, 3);
// targer 0 위치에 3부터 시작해서 끝까지의 값을 복사
// 40 50 60 40 50 60
let new_array = n6.copyWithin(1, 2, 5);
// targer 1 위치에 2부터 시작해서 4까지의 값을 복사
// 10, 20, 30, 40, 50, 60 -> 10 30 40 50 50 60
console.log(new_array);
const elements = ['Fire', 'Air', 'Water']
console.log("12. 배열의 문자열을 하나의 문자열로 조인(연결): ");
console.log(elements.join()); // "Fire,Air,Water"
console.log(elements.join('-')); // "Fire-Air-Water"
console.log(elements.join(' ')); // "Fire Air Water"
var n7 = [4, 2, 5, 1, 3];
n7.sort();
console.log("13. 오름차순 정렬: ", n7); // 1 2 3 4 5
var n7 = [14, 22, 65, 1, 34];
n7.sort();
console.log("13-1. 오름차순 정렬: ", n7); // 1 4 22 34 65
// 내림차순 정렬은 함수이용해서 명시적으로 구현해야 됨.
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function (a, b) {
// return a-b; // 오름차순
return b - a; // 내림차순
});
console.log("13-2. 내림차순 정렬: ", numbers); // 5 4 3 2 1
// sort(함수); <== 가능한 이유가 함수는 데이터이기 때문이다.
// 기본반복(forEach), 가공(map), 필터링(filter)
var n8 = [14, 22, 65, 1, 34];
console.log("14. 기본 반복처리");
// n8.forEach(function (v) {
// console.log(v); // value
// });
// n8.forEach(function (v, i) {
// console.log(v, i); // value, index
// });
n8.forEach(function (v, i, arr) {
console.log(v, i, arr); // value, index, 배열
});
console.log("15. 가공처리(* 사용빈도 높음): ");
// let new_array2 = n8.map(function (v) {
// // 가공전
// console.log(v);
// return v;
// });
// console.log(new_array2);
let new_array2 = n8.map(function (v, i, arr) {
// this -> { mesg: "hello" }
// this.mesg -> "hello"
console.log(v, i, arr, this, this.mesg);
return v * 2;
}, { mesg: "hello" });
console.log(new_array2);
console.log("16. 필터링: ");
// let new_array3 = n8.filter(function () {
// return true; // 조건이 true 인 경우에만 반환됨.
// });
// console.log(new_array3);
let new_array3 = n8.filter(function (v, i, arr) {
// 조건: 짝수
return v % 2 == 0; // 조건이 true 인 경우에만 반환됨.
});
console.log(new_array3); // [14, 22, 34]
// 정적메서드
console.log("17. 배열 생성1: Array.of(값,값2,값3)");
var new_array4 = Array.of(10);
var new_array4 = Array.of(10, 20, 30);
console.log(new_array4); // [10, 20, 30]
console.log("17-1. 배열생성2: Array.from(유사배열[,map함수]): ");
var new_array5 = Array.from("Hello");
console.log(new_array5); // ['H', 'e', 'l', 'l', 'o']
var new_array6 = Array.from("Hello", function (v) {
return v.toUpperCase();
});
console.log(new_array6); // ['H', 'E', 'L', 'L', 'O']
</script>
</head>
<body>
</body>
</html>










3. spread 연산자 ( 전개구문 )(************************)
기능: 배열|JSON 요소를 펼치는 기능으로서
기존 배열을 펼쳐서 새로운 배열을 만들 때 사용함.
문법: [...배열]
예>
// spread 연산자 (전개 구문)
var n = [10,20,30];
var x = n; // 얕은 복사(주소값 복사, x 변경하면 n도 영향 받음)
//1. 배열 복사
var n2 = [...n]; // 깊은 복사 ( 실제값 복사, n2 변경해도 n은 영향 없음 )
console.log(n2);
//2. 기존 배열에 새로운 값을 추가
var n = [10,20,30];
var n2 = [...n, 40, 50]
var n2 = [40, 50, ...n]
console.log(n2);
//3. 배열 연결
var n = [10,20,30];
var n2 = [100,200,300];
var n3 = [...n, ...n2];
console.log(n3);
// 4. 문자열 전개
var x = [...'hello'];
console.log(x); // ['h', 'e', 'l', 'l', 'o']
<!DOCTYPE html>
<html lang="en">
<head>
<title>js08_spread연산자_전개구문</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// spread 연산자(전개구문)
var n = [10, 20, 30];
var x = n; // 얕은 복사(주소값 복사, x 를 변경하면 n도 영향 받음)
// 1. 배열복사
var n2 = [...n]; // 깊은 복사(실제값 복사, n2 변경해도 n은 영향 없음)
console.log(n2); // [10, 20, 30]
// 2. 기존 배열에 새로운 값을 추가
var n = [10, 20, 30];
var n2 = [...n, 40, 50]; // [10, 20, 30, 40, 50]
var n2 = [40, 50, ...n]; // [40, 50, 10, 20, 30]
console.log(n2);
// 3. 배열 연결
var n = [10, 20, 30];
var n2 = [100, 200, 300];
var n3 = [...n, ...n2];
console.log(n3); // [10, 20, 30, 100, 200, 300]
// 4. 문자열 전개
var x = [...'hello'];
console.log(x); // ['h', 'e', 'l', 'l', 'o']
</script>
</head>
<body>
</body>
</html>


'[study]이론정리 > HTML & CSS & JavaScript' 카테고리의 다른 글
js 3일차 - 객체(3) Window객체 (0) | 2024.05.07 |
---|---|
js 2일차 -객체(2) _ BOM (Browser Object Model) (0) | 2024.05.03 |
js 2일차 - 1일차 정리 (0) | 2024.05.03 |
js 1일차 - 연산자, 문장, 객체 (1) | 2024.05.02 |
js 1일차 - 개요, 식별자, 변수, 상수 (1) | 2024.05.02 |