Vanilla JS #6
DB에 중복된 value를 가지는 Item을 구별
item에 현재 시간값을 key값으로 지정해서 중복 value를 구별
const myObj={
name : "kim",
key : Date.now(),
}
이 값을 push하면 된다.
DB의 Item을 제거
solution : filter() 함수 이용
// list는 localStorage에 저장된 정보라 가정
function handleDelete(event) {
const DELETED_NODE = event.target.parentElement; // 클릭이 일어난 부모에 key 정보가 있음 (시간 값으로)
list = list.filter((item)=>item.key!==parseInt(DELETE_NODE.key)); // list에 filter를 이용해 삭제할 노드를 걸러냄
DELETED_NODE.remove(); // 노드 HTML 문서에서 제거
localStorage.setItem("LIST", JSON.stringify(list)); //localStorage에 새로운 list 업데이트
}
filter()
The
filter()method ofArrayinstances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
예시
function isTall(height){
return height>100;
}
const filtered=[100,101,200,10].filter(isTall);
console.log(filtered);
//OUTPUT
//[101,200]
이때 filter의 첫 인자로 들어가는 함수는 불린값(True/False)를 반환해야 한다.
그리고 filter는 array를 파괴하는 것이 아닌, 새로 array를 생성하기 때문에 기존 array에는 영향을 미치지 않는다.
WeatherAPI 이용하기
날씨 API를 제공해주는 사이트로 들어간다.
그러면 아래와 같이 API call할 수 있는 url을 제공해준다.
Geolocation: getCurrentPosition() method
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The
getCurrentPosition()method of theGeolocationinterface is used to get the current position of the device.
// 구문
navigator.geolocation.getCurrentPosition(success, error, [options]);
const API_KEY = "사이트에서 제공해주는 개인 고유의 API_KEY";
function onGeoOk(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const url = `https://api.openweathermap.org/data/2.5/weather
lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`;
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data.name, data.main.temp); // 화면에 출력
});
}
function onGeoError() {
alert("Geolocation is not supported by this browser.");
}
navigator.geolocation.getCurrentPosition(
onGeoOk,
onGeoError
);
Leave a comment