728x90
반응형
1) Javascript
1-1) Object 객체
1-2) JSON
1-3) 함수
1-4) 객체생성자 함수
1-5) HTML DOM
1) Javascript
1-1) Object 객체
08.Object객체.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Object</title>
<script>
/*
Object Properties
데이터를 구조화하고 저장하는 방법
- {name : value}의 형태
*/
// 1. 객체 리터럴
const obj1 = {
name: "홍길동",
age: 30,
};
console.log(obj1);
// 2. new Object 생성
const obj2 = new Object();
obj2.name = "강감찬";
obj2.age = 40;
console.log(obj2);
// 3. 클래스 정의 객체 생성
class Human {
// constructor 키워드 : Javascript에서 생성자임을 나타내는 키워드
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const obj3 = new Human("이순신", 50);
console.log(obj3);
// 객체의 속성 접근방법
// 1. 속성 선택자, 점 표기
console.log("---- 점 ----");
console.log(obj1.name);
console.log(obj1.age);
// 2. 대괄호 표기
console.log("---- 대괄호 ----");
console.log(obj1["name"]);
console.log(obj1["age"]);
// 객체 생성
let person = {
firstName: "길동",
lastName: "홍",
id: "hong",
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
// 객체의 속성 처리
console.log("---- 객체의 속성 처리 ----");
// 속성 추가
person.age = 30;
console.log(person);
// 속성 변경
person.lastName = "김";
person["firstName"] = "개똥";
console.log(person);
// 속성 삭제
delete person.id;
console.log(person);
// 속성 확인
console.log(person);
console.log("---- 1 ----");
console.log(person.firstName);
console.log(person.lastName);
console.log(person.fullName());
console.log("---- 2 ----");
for (let item in person) {
console.log(item);
console.log(person[item]);
}
</script>
</head>
<body></body>
</html>
1-2) JSON
09.JSON.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JSON</title>
<script>
/*
JSON(JavaScript Object Notation)은 자바스크립트
객체 표기법을 기반으로 한 데이터 교환 형식.
JSON은 사람이 읽기 쉬우면서도 기계가 쉽게 파싱하고
생성할 수 있는 형식으로, 웹 어플리케이션에서
서버와 클라이언트 간에 데이터를 교환하는데 주로 사용.
- DataType - Java - JSON
Boolean new Boolean() let a = true;
Number new Number() let b = 10;
String new String() let c = "aaa";
Array new Array() let ar = [];
Object new Object() let ob = {};
*/
// 문자열
let obj = '{"id" : "aaa", "title" : "bbb"}';
console.log("---- 문자열 ----");
console.log(obj.id);
console.log(obj["title"]);
console.log(typeof obj);
console.log("---- 문자열 => JSON 객체 ----");
let ob = JSON.parse(obj);
console.log(ob.id);
console.log(ob["title"]);
console.log("---- JSON 객체 => 문자열 ----");
// 속성에 특수기호나 공백이 들어가는 경우를 제외하면 ""로 감싸지 않아도 JSON 타입으로 인식된다!
// let obj2 = { "id" : "aaa", "title" : "bbb" };
let obj2 = { id: "aaa", title: "bbb" };
let ob2 = JSON.stringify(obj2);
console.log(typeof ob2);
window.onload = function () {
let person = {
name: "홍길동",
age: 30,
isStudent: false,
courses: ["Math", "Science", "History"],
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
},
};
// 보내는 쪽
let jsonString = JSON.stringify(person);
console.log(jsonString);
console.log(typeof jsonString);
// 받는 쪽
let jsonString2 =
'{"name":"홍길동","age":30,"isStudent":false,"courses":["Math","Science","History"],"address":{"street":"123 Main St","city":"Anytown","state":"CA"}}';
let person2 = JSON.parse(jsonString2);
console.log(person2);
console.log(typeof person2);
console.log(person2.name);
console.log(person2.courses[1]);
let contents = document.querySelector("#contents");
let str = "";
str += `<table>`;
str += `<caption>학생 정보</caption>`;
str += `<tr>`;
str += `<th>이름</th>`;
str += `<td>${person2.name}</td>`;
str += `</tr>`;
str += `<tr>`;
str += `<th>나이</th>`;
str += `<td>${person2.age}</td>`;
str += `</tr>`;
str += `<tr>`;
str += `<th>과목</th>`;
str += `<td>${person2.courses[0]}`;
str += `, ${person2.courses[1]}`;
str += `, ${person2.courses[2]}`;
str += `</td>`;
str += `</tr>`;
str += `<tr>`;
str += `<th>주소</th>`;
str += `<td>${person2.address.street}`;
str += `, ${person2.address.city}`;
str += `, ${person2.address.state}`;
str += `</td>`;
str += `</tr>`;
str += `</table>`;
// innerHTML : 대상이 되는 태그(contents) 안에 해당 값(str)을 넣어주는 역할을 수행함!
contents.innerHTML = str;
};
</script>
<style>
table,
th,
td {
border: 2px solid black;
border-collapse: collapse;
font-weight: bold;
text-align: center;
padding: 10px;
}
th {
background-color: orange;
color: white;
}
</style>
</head>
<body>
<div id="contents"></div>
</body>
</html>
1-3) 함수
10.함수.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
/*
Function
1. 함수의 문법
- 명명규칙 : 영문자, _, $ 사용 가능함 / 숫자와 특수문자는 사용 불가함
- 명명관례 : 동사로 시작하며, 두 개 이상의 단어는 Camel Case
- function 함수이름 (arg1, arg2, arg3, ...) {
// code
}
2. 리턴
- return을 만나면 함수의 실행을 중지하고 호출한 곳으로
리턴 값을 돌려준다.
- 리턴을 작성하지 않으면 undefined를 반환함.
*/
function addFunction(a, b) {
return a + b;
}
let result = addFunction(10, 20);
console.log(result);
// 함수 호이스팅 : 함수 선언이 해당 코드가 실제로 실행되기 전에 끌어올려지는 현상
// 1. 함수 선언 : 호이스팅이 발생함!
myFunc();
function myFunc() {
document.write("함수 선언<br>");
document.write("함수 정의문보다 호출문이 먼저 나와도 함수를 호출");
}
// 2. 함수 표현식 : 함수 표현식은 위의 함수 선언문과 달리 호이스팅이 발생하지 않는다!
// 함수 표현식은 변수에 할당된 익명함수 또는 이름이 있는 함수를 정의
/*
myFunc2();
var myFunc2 = function () {
document.write("함수 표현식<br>");
document.write("함수의 할당이 호이스팅되지 않아 호출 불가");
};
*/
// 내장함수
console.log(typeof parseInt("1000"));
console.log(typeof parseFloat("3.14"));
console.log(typeof String(2000));
// 숫자가 아닌 값을 숫자로 변환했을 때 NaN이 되는지 확인
console.log(isNaN("5-3"));
console.log(isNaN("53"));
console.log(isNaN(NaN)); // true
console.log(isNaN(123)); // false
console.log(isNaN("123")); // false, 숫자로 변환 가능
console.log(isNaN("abc")); // true, 숫자로 변환 불가
console.log(isNaN(true)); // false, 숫자 1로 변환 가능
console.log(isNaN(false)); // false, 숫자 0으로 변환 가능
console.log(isNaN(undefined)); // true, NaN으로 변환
console.log(isNaN(null)); // false, 숫자 0으로 변환 가능
</script>
</head>
<body></body>
</html>
1-4) 객체생성자 함수
11.객체생성자 함수.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
function CheckWeight(name, height, weight) {
this.userName = name;
this.userHeight = height;
this.userWeight = weight;
this.minWeight;
this.maxWeight;
this.getInfo = function () {
let str = "";
str += `이름: ${this.userName}`;
str += `, 키: ${this.userHeight}`;
str += `, 몸무게: ${this.userWeight} <br>`;
return str;
};
this.getResult = function () {
this.minWeight = (this.userHeight - 100) * 0.9 - 5;
this.maxWeight = (this.userHeight - 100) * 0.9 + 5;
if (
this.userWeight >= this.minWeight &&
this.userWeight <= this.maxWeight
) {
return "정상";
} else if (this.userWeight < this.minWeight) {
return "미달";
} else {
return "초과";
}
};
}
let jang = new CheckWeight("장보리", 168, 62);
let park = new CheckWeight("박달재", 180, 88);
console.log(jang.userName);
console.log(park.userHeight);
document.write(jang.getInfo());
document.write(jang.getResult());
</script>
</head>
<body></body>
</html>
1-5) HTML DOM
12.HTML DOM.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!--
DOM(Document Object Model) : 문서 객체 모델
프로그램과 스크립트가 문서의 컨텐츠, 구조, 스타일 등에
동적으로 엑세스하여 업데이트할 수 있도록 하는
플랫폼 및 언어 중립적인 인터페이스
HTML 엘리먼트 찾기
- document.getElementById(id) : id로 엘리먼트 찾기
- document.getElementsByTagName(name) : 태그 이름으로 엘리먼트 찾기
- document.getElementsByClassName(name) : 클래스 이름으로 엘리먼트 찾기
- document.querySelector(선택자) : 선택자로 엘리먼트 찾기
- document.querySelectorAll(선택자) : 선택자로 다수의 엘리먼트 찾기
HTML 엘리먼트 변경하기
- element명.innerHTML = HTML 컨텐츠
: 엘리먼트의 HTML 내용 변경
- element명.attribute(속성 이름) = 변경할 속성 값
: 엘리먼트의 속성 값 변경
- element명.style.property(CSS 속성 이름) = 변경할 스타일 값
: 엘리먼트의 스타일 변경
HTML 엘리먼트 생성하기
- document.createElement(element) : 엘리먼트 생성
- document.appendChild(element) : 엘리먼트 추가
- document.removeElement(element) : 엘리먼트 삭제
- document.replaceChild(element) : 엘리먼트 교체
- document.write(text) : HTML 쓰기
-->
</head>
<body>
<p id="demo">안녕하세요</p>
<p class="demo">안녕하세요</p>
<p class="demo">안녕하세요</p>
<input type="text" name="name" id="id" value="김길동" />
<script>
document.getElementById("demo").innerHTML = "Hello World";
document.getElementById("id").value = "홍길동";
document.getElementById("id").style.color = "red";
let button = document.createElement("button");
button.innerHTML = "전송하기";
document.body.appendChild(button);
</script>
</body>
</html>
'Javascript > Javascript(2024 version)' 카테고리의 다른 글
Javascript(6) - 예제(간단한 계산기, window) (0) | 2024.06.14 |
---|---|
Javascript(5) - 예제(class 추가/삭제, selectBox를 통한 이미지 선택, 데이터 출력, 주민등록정보 조회) (0) | 2024.06.12 |
Javascript(4) - HTML DOM 이벤트, HTML BOM, 예제(배경색 변경 / 글자수 표기) (0) | 2024.06.11 |
Javascript(2) - 연산자, 제어문, 배열, Date 객체, Math 객체, String 객체 (0) | 2024.06.05 |
Javascript(1) - 회원 가입 예제, Javascript 출력 예제 / 기본 문법(변수, 데이터 타입) (0) | 2024.06.04 |