고래씌
[HTML5api] 웹 스토리지 본문
1. Webstroage
▶ browser에 사용자데이터를 저장하는 html5 표주 api
1) sessionStorage : 서버에 접속한 동안만 기록되고, 세션이 종료되면 데이터를 삭제
2) localStorage : 만료기간이 없이 삭제전까지 데이터가 기록됨
=> Cookie나, Session과 달리 서버로 데이터가 전송되지 않는다.
1) 아이템 저장/수정하기
▶ key, value를 한쌍으로 localStorage 객체에 저장하기
- localStorage.setItem(key, value) 함수
- obj[key] = value
☞ 무조건 문자열로 저장된다!
<fieldset>
<legend>아이템 저장/수정하기</legend>
<input type="text" id="key1" placeholder="key">
<input type="text" id="value1" placeholder="value">
<input type="button" value="실행" onclick="test1();">
</fieldset>
<script>
function test1(){
// localStorage.setItem(key, value) 함수
// localStorage(setItem("id",'이고래'));
// localStorage.setItem(key1.value,value1.value);
// obj[key] = value
localStorage[key1.value] = value1.value;
}
</script>
2) 아이템 가져오기
☞ getItem(key) key값을 이용하여 값을 가져옴
<fieldset>
<legend>아이템 가져오기</legend>
<input type="search" id="key2" placeholder="key">
<input type="button" value="검색" onclick="test2();">
</fieldset>
<script>
const test2 = () => {
// getItem(key)
const value = localStorage.getItem(key2.value);
console.log(typeof value); // 무조건 문자열로 저장이 된다는 걸 알수 있음
if(value){ // new Boolean()
alert(`${key2.value} : ${value}`);
}else{
alert("조회된 데이터가 없습니다.")
}
}
</script>
3) 아이템 삭제
▶ remoeItem() : key 값에 해당하는 데이터를 삭제
▶ clear() : 로컬스토리지에 저장된 모든 데이터를 삭제
<fieldset>
<legend>아이템 삭제</legend>
<input type="search" id="key3">
<input type="button" value="삭제" onclick="test3()">
</fieldset>
<script>
function test3(){
localStorage.removeItem(key3.value);
// 안에 있는 데이터를 싹 지우고 싶다면 localStorage.clear() 하면됨
}
</script>
2. 객체 저장
▶ localStorage의 value은 모든 데이터를 string으로 저장한다.
▶ 객체를 value으로 저장하고자 할때는 toString 호출결과를 저장한다.
▶ 객체의 기본 toString 호출결과 : [object Object]
▶ 객체에 저장된 정보를 보여지게 하려면 toString 함수를 직접 재정의해야한다.
1) JSON 변환 없이 객체 저장
<input type="button" value="실행" onclick="test4();">
<script>
function test4(){
const user = { id : 'mkm',
phone : '01012341234',
married : false,
age : 35,
// toString: function(){
// return this.id + ", " + this.phone + ", "+ this.married + ", " + this.age;
// }
}
localStorage.setItem('user',user);
}
</script>
|
☞ toString을 재정의하지 않은 결과, [object Object]의 형식으로 저장이 되는 것을 볼 수 있다.
☞ 이 경우, toString의 주석을 해제하고 다시 실행하면 .... 아래와 같이 출력되는것을 볼 수 있다.
☞ 하지만,,,
▶ ★객체를 웹저장소에 저장시 항상 문자열형태로만 기록되기때문에 객체형태의 데이터를 유지할 수가 없다..★
- 해결방법 : 객체를 JSON형식으로 저장하기
- JSON ? JavaScript Object Notation의 약자로 값이나 객체를 다룰때 많이 사용되는 형식
☞ 자바스크립트 객체를 문자열 형태의 객체로 변환하거나, 문자열형태의 자바스크립트 객체를 다시 자바스크립트 객체로 변환시 사용되는 포맷이다.
☞ 특정 데이터를 주고받을 때, 전달하는 데이터를 JSON 형태의 객체로 포장하고, 받아주는 서버측(JAVA언어를 사용한다고 가정)에서는 JSON형식으로 포장된 객체를 JAVA 언어의 객체로 파싱해서 사용
2) JSON 변환 후 객체 저장
▶ 변수 = JSON.stringify(user); // 자바스크립트 객체로 JSON으로 바꿔주는 함수
▶변수 = JSON.parse(변수명); // JSON 객체를 javascript 객체로 변환
<script>
function test4(){
const user = {
id : 'mkm',
phone : '01012341234',
married : false,
age : 35,
toString: function(){
return this.id + ", " + this.phone + ", "+ this.married + ", " + this.age;
}
}
// 자바스크립트객체로 JSON으로 바꿔주는 함수
// JSON.stringify
const jsonStr = JSON.stringify(user);
console.log(jsonStr, typeof jsonStr); // 문자열로 이루어진 자바스크립트 객체
localStorage.setItem('user',jsonStr);
const getUser = localStorage.getItem('user'); // key값이 user인 값 반환
console.log(getUser); // [Object object] -> mkm, 01012341234, ...
console.log(typeof getUser) // => 객체가 아니라 문자열이다. 객체의 포맷을 그대로 가져온 것임
// JSON객체를 javascript객체로 변환
const anotherUser = JSON.parse(getUser);
console.log(anotherUser);
console.log(typeof anotherUser); // type -> object 출력 // 객체 형태로 저장됨
}
</script>
▶ JSON으로 바꾸어 저장한 후, const getUser = localStorage.getItem('user') 를 이용하여 값 반환을 하였을 때, 보이는 것은 객체로 보이지만 String 형인 것을 볼 수 있다.
=> 즉, 객체가 아니라 문자열이다. 객체의 포맷을 그대로 가져온 것임을 알 수 있다.
▶ JSON 객체를 javascript 객체로 변환한 후, (const anotherUser = JSON.parse(getUser);) console.log를 이용해 출력
=> 반환형이 objet, 즉 "객체"임을 알 수 있다!
3. 논리형으로서의 형변환
▶ 변수, 리터럴들이 boolean형으로 형변환 가능
▶ 값이 존재하는 것은 true으로 치환 : 123, -100, 3.15, '이고래', new Date(), [1], {}, h1 ...
▶ 값이 존재하지 않는 것을 false로 치환 : 0, 0.0, "", '', undefined, null, Nan, [], ...
<h2>논리형으로의 형변환</h2>
<input type="button" value="실행" onclick="test5()">
<script>
const test5 = function(){
// true로 치환되는 경우
console.log(Boolean(123));
console.log(Boolean(-100));
console.log(Boolean(3.14));
console.log(Boolean('abcde'));
console.log(Boolean(new Date()), Boolean({}), Boolean([1]), Boolean(key1)); // 모두 true 반환 // 값 자체가 들어가 있으면 모두 true인 것임
// false로 치환되는 경우
console.log(Boolean(0));
console.log(Boolean(0.0));
console.log(Boolean(""));
console.log(Boolean(undefined), Boolean(null), Boolean(NaN));
// []는 조건식에서 리터럴로 제시시 false
// Boolean 함수로 확인시 true
}
</script>