-
2023_09_24 JavaScript 공부정리개발공부/JavaScript 2023. 9. 24. 23:29
[노마드코더] 5.2강~8.2강
- 문자열.padStart(자릿수, 추가할문자) : 자릿수만큼 문자열이 없으면 추가할 문자를 문자열앞에 추가함
-padEnd는 뒤쪽에 추가함
-String()은 숫자를 문자열로 변환시켜줌
-시계 만드는 코드
const clock = document.querySelector("h2#clock");function getClock() {const date = new Date();const hours = String(date.getHours()).padStart(2, "0");const minutes = String(date.getMinutes()).padStart(2, "0");const seconds = String(date.getSeconds()).padStart(2, "0");clock.innerHTML = `${hours}:${minutes}:${seconds}`}getClock();setInterval(getClock, 1000);-Math.random() : 랜덤한 0~1사이의 수를 출력함
-Math.round() : 자연수로 반올림하여 출력함
-Math.ceil() : 자연수로 올림하여 출력함
-Math.floor() : 자연수로 내림하여 출력함
*문자열이 아닌 숫자로 반환함
-명언을 랜덤으로 뽑는 코드
const quotes = [{quote: "Where there is life, there is hope.",author: "Thomas Carlyle"},{quote: "Whether you think you can, or you think you can't--you're right.",author: "Henry Ford"},{quote: "Failure is not fatal: It is the courage to continue that counts.",author: "Winston Churchill"},{quote: "Don't aim at success — the more you aim at it and make it a target, the more you are going to miss it.",author:"Viktor Frankl"},{quote:"The people who are crazy enough to think they can change the world are the ones who do.",author:"Steve Jobs"},{quote:"Imagination is more important than knowledge. Knowledge is limited; imagination encircles the world.",author:"Albert Einstein"},{quote:"The secret of success in life is for a man to be ready for his opportunity when it comes.",author:"Benjamin Disraeli"},{quote:"The most important time in your life was now.",author:"Voltaire"},{quote:"A pessimist sees difficulty in every opportunity; an optimist sees opportunity in every difficulty." ,author :"Winston Churchill"},{quote :"Many of life’s failures are people who did not realize how close they were to success when they gave up." ,author : "Thomas Edison"}];
const quote = document.querySelector("#quotes span:first-child");const author = document.querySelector("#quotes span:last-child");
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = todaysQuote.quote;author.innerText = todaysQuote.author;- .createElement() : 태그를 만들 수 있음
- .appendChild() : 태그를 삽입할 수 있음
-랜덤 이미지를 출력하는 코드
const images = ["0.jpeg","1.jpeg","2.jpeg","3.jpeg",];
const chosenImage = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");bgImage.src = `image/${chosenImage}`document.body.appendChild(bgImage)- 이벤트가 발생했을때 만들어진 event객체를 이용해서 어떤 버튼의 이벤트인지 알 수 있음. 방법은 event내의 target에서 parentElement를 찾아내면됨.
-이벤트가 발생된 버튼의 li태그를 지우는 코드
function deleteToDo(evnet){const li = evnet.target.parentElement;li.remove();}-JSON.stringify(데이터) : 데이터를 어떤 자료형이든(객체든 배열이든) 문자열로 바꿔줌
*localStorage에 배열을 배열형태로 저장하기 위해 사용하는것. 배열을 직접적으로 저장하면 문자열로 바뀌어서 저장되기 때문에, 문자열로 바뀌더라도 배열의 형태를 유지하기 위해서 사용함.
function saveToDos() {localStorage.setItem("todos", JSON.stringify(toDos));}JSON.stringify()를 사용하지 않았을때. JSON.stringify()를 사용했을때. 값은 문자열이지만 배열의 모습으로 저장됨. -JSON.parse() : 배열의 형태를 가진 문자열을 배열로 바꾸어줌
배열형태의 문자열을 JSON.parse()을 통해 배열형으로 바꿈 - 배열.forEach(함수) : 배열의 각각의 요소를 순차적으로 함수의 argument로 넣으면서 함수를 실행시킴
-아래는 화살표함수이다. forEach()안에 함수를 넣는 대신, 함수를 직접 축약하여 다음과 같이 작성가능함.
item은 함수의 argument역할을 함(다른 이름으로 바꿔도 상관X)
parsedToDos.forEach((item) => console.log("hi", item));-Date.now() : UTC 기준으로 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리초를 반환하는 메서드
- 배열.filter(함수) : 배열의 요소를 순차적으로 함수에 적용하여 반환되는 값이 true이면 해당 배열을 살려두고, false이면 해당배열을 지우는 메서드. 다만 배열을 수정하는것은 아님. 해당 함수의 조건에 해당되는 배열을 출력하는 것일 뿐이다.
-parseInt() : 문자열을 숫자로 바꾸는 함수
function deleteToDo(evnet){const li = evnet.target.parentElement;li.remove();toDos = toDos.filter((item) => item.id !== parseInt(li.id));localStorage.setItem(TODOS_KEY, JSON.stringify(toDos));}-navigator.geolocation.getCurrentPosition(성공시 실행함수, 실패시 실행함수) : 현재위치에 대한 정보를 불러옴
function onGeoOk(position){ //맨 아래의 코드는 객체를 생성해주므로 인자를 받을 곳이 필요해서 position을 넣음const lat = position.coords.latitude;const lng = position.coords.longitude;console.log(lat, lng)}function onGeoError(){alert("Can't find you. No weather for you.")}navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError)-fetch api를 이용하여 온도, 위치, 날씨를 불러오는 코드
const API_KEY = "***"
function onGeoOk(position){const lat = position.coords.latitude;const lng = position.coords.longitude;const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&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");weather.innerHTML = `${data.weather[0].main} / ${data.main.temp}`;city.innerHTML = data.name;});}function onGeoError(){alert("Can't find you. No weather for you.")}navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError)'개발공부 > JavaScript' 카테고리의 다른 글
23_10_01 JS공부정리 (1) 2023.10.02 23_09_30 JS공부정리 (0) 2023.09.30 23_09_27 JS공부정리 (0) 2023.09.29 2023_09_23 JavaScript 공부정리 (0) 2023.09.23 2023_09_22 JavaScript 공부정리 (0) 2023.09.22