YJ의 새벽
Java Script ( 객체, JSON ) 본문
- 자바 스크립트 객체
-- 자바 스크립트의 객체는 { } 안에 Key : value 가 모여있는 형태로 작성된다. (Map 형식)
-- 자바 스크립트 객체 = { K : V , K : V , K : V } ..
-- 자바 스크립트 객체 모양의 문자열
- JSON ( JavaScript Object Notation ) 자바스크립트 객체 표기법
--> " { K : V , K : V , K : V } "
-- 자바 스크립트에서 객체 생성하는 방법
1. { } : 객체 리터럴 표기법을 이용한 생성
2. 생성자 + new 생성자( ) 를 이용한 생성
- JS 객체의 Key 는 무조건 string (묵시적 string)
-> Key 작성시 " " , 모두 string 으로 인식
EX ))) 객체예제
<button id="btn1" class="btnn">객체 생성1</button>
<div class="area2" id="div1"></div>
document.getElementById("btn1").addEventListener("click",function(){
// {} 객체 생성 및 다루기
const brand = "스타벅스";
const product = {
"pName" : "텀블러",
'brand' : "투섬플레이스",
color : ["red", "black", "silver"],
price : 30000 ,
'information' : function(){ // 객체의 기능 ,(익명함수)
console.log(brand); // '스타벅스'
// ** 객체 내부에서 this == 현재객체 **
console.log(this.pName); // "텀블러"
console.log(this.brand); // "투썸플레이스"
console.log(this.color); // color
console.log(this.price); // 30000
}
};
product.information(); // 객체 기능 호출하기.
//객체가 가지고있는 값 출력하기
const div1 = document.getElementById("div1");
div1.innerHTML="";
div1.innerHTML +="product.pName : "+ product.pName+"<br>";
div1.innerHTML +="product.brand : "+ product.brand+"<br>";
div1.innerHTML +="product.color : "+ product.color+"<br>";
div1.innerHTML +="product.price : "+ product.price+"<br>";
div1.innerHTML +="<hr>";
product.price = 25000; // product.price 값 변경
div1.innerHTML +="product.price : "+ product.price+"<br>";
// JS 객체에 없는 Key에 값 대입하기.
// --> 객체에 추가된다 !!
product.capacity = "550ml";
div1.innerHTML +="product.capacity : "+ product.capacity+"<br>";
div1.innerHTML +="<hr>";
// 객체의 Key 제거방법
// -> delect 객체변수명.Key
//delete product.color;
//div1.innerHTML +="product.color : "+ product.color+"<br>";
// 객체명 ['Key'] 방법으로
// 객체가 가지고있는 모든 값 출력하기.
// --> for in 구문 ( 객체 전용 for문 )
//for ( let Key in 객체명 )
// : 매 바퀴마다 객체의 K를 하나씩 얻어와 Key변수에 저장
for ( let key in product){
div1.innerHTML+= product[key] +"<br>";
}
})
- 생성자 함수
-- 생성자 함수의 시작은 반드시 대문자 !!!!
-- JS함수의 매개변수는 let, const , var 를 적지않음.!!
--> 안적어도 해당 함수의 지역변수로 취급.
-- 생성자 함수에서의 this
--> new 연산자를 통해서 만들어지는 객체 ( 앞으로 만들어질 객체 )
<button id="btn2" class="btnn">객체 생성2</button>
<div class="area2" id="div2"></div>
// 생성자 함수
// 111 생성자함수 정의
function Student(grade, ban, name){
// JS 함수의 매개변수는 let, const, var 를 적지않음.!!
//속성
this.grade = grade;
this.ban = ban;
this.name = name;
//기능
this.introduce = function(){
return this.grade + "학년 "+ this.ban+ "반 "+this.name;
}
}
document.getElementById("btn2").addEventListener("click",function(){
const div2 = document.getElementById("div2");
const stdList = [] ; // 빈배열 생성
// 222 생성자 함수 호출 : new 생성자함수명(매개변수)
stdList.push(new Student (1 , 2 , "홍길동"));
stdList.push(new Student (2 , 3 , "차길동"));
stdList.push(new Student (3 , 4 , "지길동"));
stdList.push(new Student (1 , 7 , "남궁길동"));
div2.innerHTML="";
// for of : 배열/ 컬렉션 요소 반복접근용 for문
for(let std of stdList){
//for in : 객체의 키 반복 접근용 for문
for (let key in std) {
// std[Key] 의 자료형이 'function' 이면 실행후출력해라.
if(typeof std[key]=='function'){
div2.innerHTML+=key+" : "+ std[key]() + "<br>";
}else{
div2.innerHTML+=key+" : "+ std[key] + "<br>";
}
}
div2.innerHTML+="<hr>"
}
})
- JSON ( JavaScript Object Notation ) 자바스크립트 객체 표기법
-- JS 객체 : { "memberId" : "user01" , "memberPw" : "pass01" , "age" : 20 }
-- JSON 문자열 : ' { "memberId" : "user01" , "memberPw" : "pass01" , "age" : 20 } '
-- 간단한 포맷.
- 괄호 { } 내에 key : value 쌍으로 구성 { "key" : value }
- key : 반드시 문자열 !!
- value : String , Number , Boolean , Array , Object , null .... 데이터 저장 가능
-- 객체 { } 또는 배열 [ ] 데이터를 효율적으로 표시 가능
-- 경량 데이터 교환 방식.
-- 간단한 포맷을 가지고있어 이해하기 쉬움.
-- 순수 TEXT 기반 , 구조화된 TEXT 형식
-- 대부분의 프로그래밍언어에서 JSON 포맷 데이터를 핸들링할수있는 라이브러리 제공.
( 시스템간 객체 교환에 용이 )
- JavaScript JSON 내장 객체
-- JSON 포맷의 데이터를 간편하게 다룰 수 있도록 내장된 객체
-- JSON . stringify( JS객체 ) : JS 객체 --> JSON 문자열 변환 .
-- JSON . parse (JSON문자열) : JSON문자열 --> JS 객체 변환 .
-- JSON 변환시 객체의 기능은 포함하지 않는다 !!!
-- JSON 은 데이터 전달에 특화된 형태.
<button id="btn3" class="btnn">확인하기</button>
document.getElementById("btn3").addEventListener("click",function(){
const std = new Student(5,7,"김철수");
console.log(std); // 객체
console.log(JSON.stringify(std)); // 객체 --> JSON 변환
// ** JSON 변환시 객체의 기능은 포함하지않는다!!
const member='{"memberId":"user01" , "memberPw":"pass01", "age":20}';
console.log(member); // JSON 문자열
console.log(JSON.parse(member)); // JSON --> 객체 변환
})
'WebFront_ > Java Script' 카테고리의 다른 글
Java Script ( 요소 추가 제거 ) (0) | 2023.03.02 |
---|---|
Java Script ( 노드(Node), 요소(Element) 탐색 ) (0) | 2023.03.02 |
Java Script ( window 내장객체 , 팝업창 ) (0) | 2023.02.28 |
Java Script ( 형변환, 연산자, 배열 ) (0) | 2023.02.28 |
Java Script ( 정규표현식 ) (0) | 2023.02.27 |