목록프로그래밍/JavaScript (52)
쌓고 쌓다
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/bZ9YaT/btrWkvPXVRt/miJdPeMN8rf0TFjaLV6Q60/img.png)
행맨 게임을 만들기위해 API를 이용해 랜덤 단어를 가져오는 부분을 알아보고 있었다. 그런데 통신하여 단어를 가져오는건 잘 되는데 출력을하면 undefined만 뜨는것이다... 여기에 2가지 문제를 겪었고 이해했다. 처음 API를 써보는거라 바보 같았지만 꼭 짚고 넘어가야할 부분이였다. 첫번째 문제 async function getPuzzle() { axios.get('https://puzzle.mead.io/puzzle?wordCount=1') .then((result) => { console.log('성공:', result.data.puzzle) return result.data.puzzle }) } getPuzzle().then(console.log) then으로 가져온것을 출력해보아도 잘 나오지만..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/bRsWCg/btrWbMsH10U/5rHhKDTf7B8oJA1QJfTRd0/img.png)
비동기 처리의 필요성 function fetchUser() { // 10초 걸림 return '홍길동' } const user = fetchUser() console.log(user) 사용자의 데이터를 가져오는 함수 fetchUser가 있다고 하자. 이것이 처리되는데 10초가 걸린다고 가정하면. 자바스크립트는 동기적인 처리를 하기 때문에 fetchUser가 끝날 때까지 머무르게 된다. 이후에 웹 페이지 UI를 표시하는 코드들이 있다면 10초가 걸리는 동안 사용자는 텅텅 빈 페이지를 보게 된다. 그래서 비동기적인 처리를 위해 promise를 사용한다. Promise 적용 function fetchUser() { return new Promise((resolve, reject) => resolve('홍길동'..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/NXgL2/btrV6dQlxkQ/lHdyC6FV7l5lYjxbxCYwEk/img.png)
콜백 함수 매개변수로 전달하는 함수를 콜백 함수라고 한다. 콜백함수는 즉시 실행할 수도 있고, 나중에 실행할 수도 있다. 동기 콜백(Synchronous callback) function printImmediately(print) { print() } printImmediately(() => console.log('즉시 콜백함수 실행')) 비동기 콜백(Asynchronous callback) function printWithDelay(print, timeout) { setTimeout(print, timeout) } printWithDelay(() => console.log('async callback'), 2000) 콜백 지옥 아래의 콜백 함수 add가 있다고 하자. function add(x, cal..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/dinZgf/btrVPH6kGgN/H3HTXBB3WcU5a7fFspWRmk/img.png)
static 속성 및 메소드는 정적 속성, 정적 메소드라고 부른다. static 속성과 메소드는 객체를 생성하지 않고 사용할 수 있다. static 속성 및 메소드 생성 형태 class 클래스이름 { static 속성 = 값 static 메소드() { ... } } static 속성 및 메소드 사용법 클래스이름.속성 클래스이름.메소드() Counter 클래스 class Counter { static #privateCount = 0 static count = 0 constructor(){ Counter.count+=1 // 생성자에서 this.#count+=1로 불가 } static get getCount(){ return Counter.count } } static은 private과 결합이 가능하다. s..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/bfmG9L/btrVOA6MaaP/E87xmo225B966YHwQHH6rK/img.png)
아래와 같이 정사각형 클래스가 있다고 하자. class Square { constructor(length) { if(length
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/baKZuo/btrVQnEXUUK/FIEW4vmKoAfMMr56qQHTXk/img.png)
상속 상속의 필요성을 이해해 보자. 사각형 클래스와 정사각형 클래스를 먼저 만들어 본다. 사각형 클래스 class Rectangle { constructor(width, height) { this.width = width this.height = height } // 둘레 계산 getPerimeter() { return 2 * (this.width + this.height) } // 넓이 계산 getArea() { return width * height } } 정사각형 클래스 class Square { constructor(length) { this.length = length } // 둘레 계산 getPerimeter() { return 4 * this.length } // 넓이 계산 getArea()..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/VOexH/btrVIwoQh6d/mOmf86pwt243aijKChOt31/img.gif)
실행 결과 기능 1. 텍스트 입력 후 추가버튼 클릭 시 목록에 추가. 2. 목록의 좌측 체크박스를 클릭시 취소선 발생. 3. 삭제 버튼 클릭시 목록을 제거 코드 구현 1. body 부분 To Do List 추가 example 삭제 아직 html과 css를 공부하지 않아서 div가 정확히 무엇인지 모르겠으나 영역을 나누는 태그 같다. 이것을 할 일 리스트를 분할하였고 그 안에서도 div로 목록마다 영역을 만들어 추가하는 방식이다. 목록을 넣기위해 입력하는 부분의 id를 "toDo" 목록의 내용을 추가하는 버튼을 "addButton" 목록들을 가지는 목록 리스트를 "toDoList"로 분할하였다. 각 할일 목록은 아래의 형태로 구성한다. 체크박스를 위한 input 태그와 내용을 위한 span 해당 목록 삭제..
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/kJy6p/btrVAaUNSyD/iGrh5FKkHiJpKzCKVC1ss1/img.png)
먼저, 클래스를 사용하지 않고 객체를 생성하여 사용하는 방법들을 보이겠다. 객체 배열 생성 const students = [] students.push({이름: '홍길동', 국어: 10, 영어: 10}) students.push({이름: '철수', 국어: 20, 영어: 20}) console.log(JSON.stringify(students, null, 2)) students 배열에 객체들을 넣었다. 객체 배열 조회 let output = '이름\t국어\t영어\n' for(const s of students) { output += `${s.이름}\t${s.국어}\t${s.영어}\n` } console.log(output) 객체를 처리하는 함수 선언 및 출력 function getSumOf(student)..