Coding Archive

노마드 코더 - 바닐라 JS로 크롬 앱 만들기(10) 본문

🖥️ Clone Coding

노마드 코더 - 바닐라 JS로 크롬 앱 만들기(10)

코등어 2022. 6. 19. 01:33

7. Deleting To Dos part Two

forEach 함수는  painToDo를 pasrsedToDos배열의 요소마다 실행한다.

기억해야 할 건 forEach는 painToDo를 기본적으로 실행하는데, 각각의 item을 준다.

fliter를 사용해 앞서 배웠던 forEach와 비슷한 작업을 한다.

 

 

fliter 함수를 사용하면

→ array에서 뭔가를 삭제할 때 실제로 array에서 지우는 게 아닌 지우고 싶은 item을 빼고 새 array를 만든다.

(item을 지우는 게 아닌 item을 제외하는 것)

function sexyFilter(){return true}  // array의 item을 유지하고 싶으면 반드시 true를 return해야 한다.

[1,2,3,4,5].filter(sexyFilter)

->[1, 2, 3, 4, 5]

 

function sexyFilter(item){return item !== 3}  // item이 3이 아니면 true를 리턴

[1,2,3,4,5].filter(sexyFilter)

->[1, 2, 4, 5]

 

const arr = ["pizza", "banana", "tomato"]

function sexyFilter(food){return food !== "banana"}  // arr에서 banana를 제외한 나머지를 리턴

arr.filter(sexyFilter)

->['pizza', 'tomato']

 

const arr = [1234, 5454, 223, 122, 45, 6775, 344] 

function sexyFilter(potato){return potato <= 1000}  // -> 1000보다 큰 수를 모두 제외한 나머지를 리턴

->[223, 122, 45, 334]

 

todo를 text로 삭제하기

const todos = [{text:"lalala"}, {text:"lololo"}]

function sexyFilter(todo){return todo.text != "lololo"}

todos.filter(sexyFilter)

->{text: 'lalala'}

함수(sexyFilter)의 argument는 항상 달라도 상관없다. 

js가 array의 각 item을 sexyFunction의 첫 번째 인자로 전달해준다.

 

 

==> 정리

filter 함수 = 지우고 싶은 item을 빼고 새 array를 만든다. 그래서 예전 array는 여전히 있다.

Filter 함수는 반드시 true를 리턴해야 한다. 

만약 false를 리턴하면 그 item은 새 array에 포함되지 않을 것이다.

함수(sexyFilter)의 argument는 항상 달라도 상관없다. js가 array의 각 item을 sexyFunction의 첫 번째 인자로 전달해준다.

 

 

 

8. Deleting To Dos part Three

array의 item에 id = number 타입, li의 id = string 타입이라고 나온다.

그 이유는 createElement 때문이다.

li는 DOM을 직접 건드린 건데, DOM의 id는 문자열이라고 나와 있다. 즉 우리가 newTodo.id로 number를 넣어주었어도, DOM에선 string으로 형태 변환해서 받아들이는 것 같다.

 

paintTodo 함수 내의

const li = document.createElement("li");
li.id = newTodo.id;

이 부분 때문에 element로 만들어진 id는 string으로 인식한다.

=> parseInt로 number로 바꿔줘야 같은 number로 인식하고 삭제가 가능하다.

*parseInt는 문자열을 숫자로 바꾼다.

 

function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
toDos = toDos.filter((toDo)=> toDo.id !== parseInt(li.id));  // (toDo) => 는 return 을 대신
saveToDos();
}

 

 

+) Q

li.remove(); 에 의해서 li element가 삭제됐는데,

toDos = toDos.filter(toDo=> toDo.id !== parseInt(li.id)); 에서 li.id값을 가지고 와서 삭제할 수 있는지?

혹시 li.remove()는 HTML에서만 element를 삭제하고, JS에서는 삭제되지 않고 메모리에 남아있는 건지?

-

li.remove() deletes it from the UI but we can still access the variable.

(li.remove()는 UI에서 그것을 삭제하지만 우리는 여전히 변수에 접근할 수 있다.)

 

 

toDos.filter((toDo) => toDo.id !== parseInt(li.id)); 이 코드에서 parseInt 말고도 Number로 쓸 수 있다.

 

 

 

 

 

#8 WEATHER

 

0. Geolocation

function onGeoOk(position) {
  const lat = position.coords.latitude;
  const lng = position.coords.longitude;
  console.log("You live in", lat, lng);
}

function onGeoError() {
  alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

1. navigator 함수를 이용해 사용자의 위치를 알아내는 코드를 작성한다.

navigator.geolocation.getCurrentPosition( )라는 코드를 작성하는데, 

이때 getCurrentPosition은 2개의 argument가 필요하다.

앞쪽에는 모든 게 잘 됐을 때 실행될 함수인 onGeoOk 함수를,

뒤에는 실패했을 때 실행될 함수인 onGeoError 함수를 입력한다.

인수로 성공 시 받는 함수와 에러시 받는 함수가 둘 다 있어야 한다.

 

2. onGeoError() 함수가 실행될 때 :

에러가 발생했다는 것을 사용자에게 알려주기 위해서

alert("Can't find you. No weather for you."); 를 입력해준다.

 

3. onGeoOk 함수가 실행될 때:

function onGeoOk(position){

const lat = position.coords.latitude;

const lng = position.coords.longitude;

console.log("You live in", lat, lng);

}

자바스크립트가 position으로 user의 위치를 전달해준다.

position은 object이고 위도와 경도 값이 들어있다.

위도와 경도를 변수로 저장하고, console.log를 해서 보여준다.

 

*API 계정 열기&로그인 - https://openweathermap.org/api

-> 우리가 있는 장소의 위치와 현재 날씨를 알려준다.

1. Weather API

기본적으로 API는 다른 서버와 이야기할 수 있는 방법으로, 지금은 open weather map서버와 이야기할 것이다.

current weather data API문서를 클릭하면 위치에 대한 현재 날씨를 얻을 수 있다.

API KEY는 내 profile에 가서 가져올 수 있다. 

fetch를 사용하면 실제로 url에 갈 필요 없이 js가 대신 url을 부른다.

화씨온도를 섭씨온도로 바꾸고 싶다. (url 뒤에 &units=metric을 추가)

url을 fetch하고 그다음에 response를 받아야 한다.

 

java script

const API_KEY = "26895cbdb555cb09cae137bb89793110";

function onGeoOk(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      const weather = document.querySelector("#weather span:first-child");
      const city = document.querySelector("#weather span:last-child");
      city.innerText = data.name;
      weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    });
}

function onGeoError() {
  alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

*받은 api 링크가 브라우저에서 깔끔하게 보이지 않으면 크롬 확장 프로그램 중에 Json viewer를 설치하면 된다

 

 

html

 <div id="weather">
      <span></span>
      <span></span>
    </div>

 

 

 

 

+) Q

API_KEY를 String으로 정의해주는 이유가 있을까? (" "없이 저장하면 오류가 발생)

-

url 주소를 string으로 만들어서 변수로 저장해 야하기 때문에 API_KEY도 ""으로 감싸서 string으로 바꿔줘야 한다.

""으로 감싸주지 않으면 number+string으로 짬뽕된 타입이라 js가 읽지 못한다.

 

Comments