10월, 2018의 게시물 표시

ECMAScript6 - Spread

이미지
Spread 연산자는 이터러블 오브젝트의 엘리먼트를 분리하여 전개한다. 전개한 결과를 변수에 할당하거나 함수의 파라미터로 사용할 수 있다. 1. Array 오브젝트 2. String 오브젝트 3. 함수의 파라미터로 사용 ...rest 파라미터 Array-like Array는 아니지만 Array처럼 사용할 수 있는 Object 오브젝트를 Array-like라고 한다. ES6 스펙에서 사용하는 공식 용어. key값이 0부터 시작해서 1씩 증가하고 length 프로퍼티가 있어야한다. 둘 중 하나라도 만족하지 않으면 Array-like가 아니다. ...rest파라미터와 Arguments Argument 는 function 키워드로 함수를 정의 했을 때 사용이 가능하다. get(1,2,3)으로 호출했을 때, 호출받는 함수의 arguments에 1,2,3이 설정된다. arguments도 Array-lik e이므로 for()문으로 전개가 가능하다. 따라서 Array 오브젝트와 메서드를 사용이 불가능하다. 단점  - 함수안의 코드를 보아야 arguments의 사용 여부와 사용 부분을 알 수 있어 코드 가    독성이 떨어진다. 많은 코드를 디버깅하거나 소스 코드를 리팩토링할 때 부담이 된다. ...rest 파라미터는 arrow function 으로 함수를 정의 했을 때 사용이 가능하다. ...rest 파라미터는 Array 오브젝트로 이터러블 오브젝트이다. 따라서 Array 오브젝트의 메서드를 사용할 수 있다. 장점 - 함수안의 코드를 체크하지 않고 (one, ...rest) 형태만 보아도 rest 파라미터의 범위를 알 수 있다.

ECMAScript6 - Iteration

이미지
이터러블 프로토콜은 오브젝트의 반복 처리 규약을 정의한다. 내장 오브젝트로 String, Array, Map, Set, TypedArray, Argument 오브젝트는 디폴트로 이터러블 프로토콜을 갖고 있다. 또한 DOM의 NodeList도 갖고 있다. 이러한 오브젝트는 자바스크립트 엔진이 렌더링될 때 이터러블 프로토콜이 설정된다. 사전처리 없이 반복 처리가 가능하다. 이터러블 프로토콜이 설정된 오브젝트를 이터러블 오브젝트라고 한다. 이터러블 오브젝트는 Symbol.iterator가 있어야 한다. 이것이 이터러블 프로토콜 이다. 이터러블 오브젝트가 아닌 오브젝트에 Symbol.iterator를 개발자 코드로 추가하면 이터러블 오브젝트가 된다. Array 오브젝트가 할당된 arrayObj에서 Symbol.iterator의 존재 여부를 체크하는 코드이다. 오브젝트에 프로퍼티 존재 여부를 체크할 때 arrayObj.propertyKey 또는 arrayObj[propertyKey] 형태로 작성하는데, Symbol은 arrayObj.Symbol.iterator 형태로 작성할 수 없고 arrayObj[Symbol.iterator]와 같이 대괄호 [] 안에 Symbol.iterator를 작성해야 한다. Object 오브젝트는 이터러블 오브젝트가 아니다. Symbol.iterator가 없다. 이터레이터 프로토콜은 오브젝트 값을 순차적으로 처리할 수 있는 방법을 제공하는데, 이것이 next() 메서드이다.

ECMAScript6 - arrow function, () => {}

이미지
기본 형태 () => { }; 1. 함수 블록 { } 사용하지 않은 형태, 2. 파라미터가 한 개의 형태 3. 파라미터가 없는 형태 4. 오브젝트를 리턴 할 경우 4-1 { }가 함수 블록인지 오브젝트를 의미하는것인지 헷갈리기 때문에 ( ) 감싸주는것 같다. 4-2 아니면 아래와 같이 명시적으로 return문을 작성해준다. 5. arguments 사용 불가 function 키워드로 선언한 함수를 sports(1,2) 형태로 호출하면 함수의 arguments에 1과 2가 설정된다. 반면 화살표 함수에는 arguments가 존재하지 않는다. 화살표 함수블록에서 arguments를 사용하면 ReferenceError가 발생한다. ES6에서는 arguments 대신에 rest 파라미터를 사용한다. rest 파라미터는 "let sports = (...rest) => {code}" 형태와 같이 소괄호 () 안에 점(.)을 세 개 작성하고 이어서 파라미터 이름을 작성한다. sports(1 ,2)로 호출하면 1과 2가 rest 파라미터에 배열로 설정된다. arguments는 Argument 오브젝트를 대신하는 프로퍼티로 함수가 호출되면 Argument오브젝트를 생성하고 함수 실행이 끝나 빠져나올 때 삭제한다. 함수를 100번 호출하면 100번 Argument 오브젝트를 생성하고 삭제하므로 효율이 떨어진다. rest 파라미터는 Argument 오브젝트를 생성하지 않으므로 효율이 높다. 이런 점을 고려하여 Argument 오브젝트를 생성하지 않는 것으로 간주된다. 6. this와 setTimeout() setTimeout()가 window 오브젝트 함수이므로 setTimeout()안 this가 window 오브젝트를 참조하게 된다. 그래서 콘솔에 true가 출력된다. 여기서 문제는 newSports.get() 형태로 호출했으므로 this가 newSports의 인스턴스를...

ECMAScript6 - var와 let

이미지
1. 함수 안에 작성한 let 변수는 함수가 스코프. 2. 함수안에 if(a==0){let sprots= "축구"} 형태로 코드를 작성했을 때, sports 변수는 함수가     스코프가 아니라 if문의 블록 { } 스코프. 3. 같은 스코프에서 같은 이름의 let 변수를 선언할 수 없다. 4. let 변수는 호이스팅(hoisting) 되지 않는다. 5. let과 this 6. for문에서 var 와 let 1. 의 예시 2. 의 예시 호이스팅이란 - 변수나 함수를 선언, 정의하기 앞서서 먼저 호출하는 경우 문제없이 작동되도록 하는 특성이다. 4. 의 예시 - var 로 선언된 sports 변수는 비록 undefined가 출력되었지만 변수로 인식되었다. 반면에  let 으로 선언된 music 변수는 변수로 인식되지 않았다. 5. 의 예시 var로 선언한 변수의 스코프는 글로벌 오브젝트이고 this가 글로벌 오브젝트를 참조한다. this가 window 오브젝트를 참조한다. 6. 의 예시 for문에서 let 변수는 반복할 때마다 스코프를 갖는 반면, var 변수는 스코프를 갖지 않는다. <!doctype html> <html> <head>   <meta charset="utf8" /> </head> <body>   <ul>     <li>1~10</li>     <li>11~20</li>     <li>21~30</li>   </ul>   <script>     var nodes = document.querySelector('ul');     f...

C언어 fwrite() fread()로 enum, struct 읽고 쓰기

#include <stdio.h> #include <errno.h> #include <string.h> typedef enum _product_size {SIZE_S = 1 , SIZE_M, SIZE_L, SIZE_XL, SIZE_XXL} PRODUCT_SIZE; typedef enum _product_type {TYPE_OUTER= 1 , TYPE_TOP, TYPE_BOTTOM} PRODUCT_TYPE; typedef struct _cloth { char product_name[ 64 ]; unsigned product_price; char brand_name[ 64 ]; PRODUCT_TYPE product_type; PRODUCT_SIZE product_size; } cloth; void printPS (PRODUCT_SIZE ps); void printPT (PRODUCT_TYPE pt); int main ( int argc, char const *argv[]) { /* code */ FILE *outfile = NULL ; FILE *infile = NULL ; int i = 0 ; int num_cloth = 0 ; cloth temp_product = { 0 }; printf ( "How many products are here?" ); scanf ( "%d" , &num_cloth); if (num_cloth > 0 ){ outfile = fopen ( "C: \\ temp \\ cloth.dat" , "w" ); if ( NULL != outfile){ ...

C언어 Union과 Enum

#include <stdio.h> typedef enum _GradeType { TYPE_GRADE, TYPE_SCORE} GradeType; typedef struct _my_score { GradeType type; union { char grade; int score; } result; } my_score; int main () { int grade_type = TYPE_GRADE; my_score s1 = { 0 }; printf ( "GradeType input : ( 0 : Grade, 1 : Score)?" ); scanf ( "%d" , &grade_type); switch (grade_type){ case TYPE_GRADE: { char temp[ 10 ] = { 0 }; printf ( "input Grade ( A ~ F )" ); scanf ( "%s" , temp); s1. result . grade = temp[ 0 ]; break ; } case TYPE_SCORE: printf ( "input Score ( 0 ~ 100 )" ); scanf ( "%d" , &s1. result . score ); break ; default : printf ( "Wrong Type" ); ...

C 언어 함수에 구조체 변수 전달과 반환

#include <stdio.h> #include <stdlib.h> #include <string.h> struct s_student { char name[ 20 ]; int age; long number; }; void print_student_info ( struct s_student student); void input_student_info ( struct s_student *pStudent); int main ( int argc, char const *argv[]) { /* code */ struct s_student student = { "NAM" , 28 , 60121315 }; printf ( "Initial Value \n " ); print_student_info (student); input_student_info (&student); printf ( "After Calling Function input_student_inf() \n " ); print_student_info (student); return 0 ; } void print_student_info ( struct s_student student) { printf ( "Name : %s \t Age : %d \t Number : %ld \n " , student. name , student. age , student. number ); } void input_student_info ( struct s_student * pStudent) { if ( NULL != pStudent) { printf ( "Student Name ? " ); scanf ( "%s...

Visual Studio Code Window에서 C/C++ 빌드및 실행

이미지
비주얼 스튜디오 코드는 이미 설치가 끝났다는 전제하에 그리고 한글팩을 이미 설치했다는 전제하에서 진행해보겠습니다. C/C++을 지원해주는 확장팩을 깔아줍니다. 그리고 윈도우용 gcc, g++ 컴파일러를 설치해줍니다. 아래 사진참고 Installer를 실행한 다음, 아래사진과 같이 초록색으로 마킹 되어 있는 것들을 체크후 설치 해줍니다. 아래사진은 이미 설치하고 나서의 화면입니다. 그리고 환경변수 Path에 MinGW 설치경로를 잡아줍니다. 설치 후 cmd에 확인! 아래의 간단한 코드를 빌드하고 실행해보겠다. 아래와 같이 터미널탭에서 빌드 작업 실행을 누른다. 아래와 같은 화면이 뜨는데 오른쪽 빌드 작업 구성... 을 클릭한다. 아래처럼 바뀌는데 Others를 다시 클릭한다. 그리고 아래처럼 바뀌면 다시 클릭 그러면 아래와 같이 tasks.json 파일이 생성된다. 아래 처럼 코드를 바꾼다. 두가지 task가 있는데 build_c, exec_c 이다. 직관적인 이름 그자체로 build_c는 c언어로 짜여진 소스를 컴파일 해주는 작업이고 exec_c는 컴파일된 파일을 실행시켜주는 작업이다. 이제 아까 했던 터미널탭에서 빌드 작업을 실행 하고, 그다음 작업 실행을 누르고 exec_c를 선택하면 아래처럼 빌드 하고 실행한다. 혹시 더 괜찮은 방법이 있으면 댓글로 알려주세요~ 아래 블로그를 참고해서 제가 직접 실습한 것을 블로깅했습니다. http://webnautes.tistory.com/1158 그럼 이만 허접의 기록입니다.

C 언어 자기 참조 구조체

#include <stdio.h> #include <stdlib.h> struct linked_list {         char name[20];         int age;         struct linked_list *left_link;         struct linked_list *right_link; }; int main() {         struct linked_list first_person =  {"남동길", 28, NULL, NULL};         struct linked_list second_person = {"아무개", 30, NULL, NULL};         struct linked_list third_person = {"박서방", 35, NULL, NULL};         first_person.right_link = &second_person;         second_person.left_link = &first_person;         second_person.right_link = &third_person;         third_person.left_link = &second_person;         printf("첫번째 사람 : %s\t%d\n",first_person.name, first_person.age);         prin...

C 언어 구조체 배열의 동적 할당

포인터변수를 선언하고 malloc()함수를 사용해서 메모리를 할당하고 free()함수로 해제 #include <stdio.h> #include <stdlib.h> struct s_teacher {         char name[20];         int age;         long number; }; struct s_student {         char name[20];         int age;         long number;         struct s_teacher* pTeacher; //포인터 변수 }; void inputCounts(int *sCnt, int *tCnt); int main() {         int sCnt =0, tCnt =0;         inputCounts(&sCnt, &tCnt);         if(sCnt <= 0 || tCnt <= 0)         {                 printf("선생과 학생수는 1명 이상이여야 됩니다.\n");                 return 0;         }         printf("선생 수 : %d, \t 학생 수  : %d\n", ...

C 언어 구조체의 포인터 멤버 변수

학생11, 학생21은 선생1을 담임선생으로, 학생21, 학생22는 선생2를 담임선생으로 두고 있는 코드이다. #include <stdio.h> struct s_teacher { char name[20]; int age; long number; }; struct s_student { char name[20]; int age; long number; struct s_teacher* pTeacher; //포인터 변수 }; int main() { struct s_student student11 = {"Lee", 20, 4567}; struct s_student student12 = {"Park", 21, 4568}; struct s_student student21 = {"Choi", 20, 4567}; struct s_student student22 = {"Han", 21, 4568}; struct s_teacher teacher1 = {"Kim", 35, 1234}; struct s_teacher teacher2 = {"Nam", 28, 1235}; student11.pTeacher = &teacher1; student12.pTeacher = &teacher1; student21.pTeacher = &teacher2; student22.pTeacher = &teacher2; printf("포인터를 이용한 구조체 변수 접근\n"); printf("학생 %s의 담임교사 이름 : %s\n", student11.name,student11.pTeacher->name); printf("학생 %s의 담임교사 교번 : %ld\n",student12.name,student...

C 언어 중첩구조체 활용과 구조체 포인터를 사용한 직사각형 좌표 출력

s_rectangle 구조체는 중첩구조체로 left_top이라는 s_point 구조체 멤버변수를 가진다. 직사각형의 너비와 너비를 입력받아 나머지 right_top, left_bottom, right_bottom 좌표를 출력해주는 코드이다. #include <stdio.h> struct s_point {         int x;         int y; }; struct s_rectangle {         struct s_point left_top;         int width; //너비         int height; //높이 }; void print_rectangle_info(struct s_rectangle rectangle); void input_rectangle_info(struct s_rectangle *pRectangle); int main() {         struct s_rectangle rectangle = {0};         input_rectangle_info(&rectangle);         print_rectangle_info(rectangle);         return 0; } void input_rectangle_info(struct s_rectangle *pRectangle) {         if(NULL != pRectangle)         {              ...

C 언어 중첩 구조체 선언과 초기화

#include <stdio.h> struct s_teacher { long number; char name[20]; int age; }; struct s_student { sturct s_teacher nested_teachar; long number; char name[20]; int age; int score; }; void print_student_info(struct s_student student); int main() { struct s_student student1 = {{1234,"Kim", 35}, 4567, "Lee", 20, 30 }; struct s_student student2 = {{1234,"Choi"}, 4568, "Lee", 20, 30 }; // 선생 age는 자동으로 0으로 초기화 struct s_student student3 = {1234,"Kim", 35, 4569, "Bak", 21 }; //학생 score는 자동으로 0 으로 초기화 print_student_info(student1); print_student_info(student2); print_student_info(student3); return 0; } void_student_info(struct s_student student) { printf("이름 : %s\t 나이 : %d\t 학번 : %ld\t 점수 : %d\n", student.name, student.age, student.number, student.score); printf("담임선생 이름 : %s\t 담임선생 나이 : %d\t 담임선생 번호 : %ld\n",student.nested_teacher.name, student.nested.age,...

C 언어 구조체 배열 선언과 초기화 방법들

1. 선언과 동시에 0으로 초기화 2. memset() 함수를 이용한 초기화 3. 초기화 목록을 이용한 초기화 4. 반복문을 이용한 초기화 #include <stdio.h> #include <string.h> struct student {         char name[20];         int age;         long number; }; int main() {         //1. 선언과 동시에 0으로 초기화         struct student students[3] = {0};         //2. memset() 함수를 이용한 초기화         struct student students2[3];         memset(students2,0,sizeof(students2));         //3. 초기화 목록을 이용한 초기화         struct student students3[3] = {                 {"kim", 25, 45607},                 {"기리",28,60121315},                 {"Lee",23, 45609}         };         //4. 반...

C 언어 1차원배열 2차원 배열을 활용한 학생관리

학생 수를 입력받아서 국어점수 배열, 영어점수 배열, 수학점수 배열, 총점수 배열과, 학생이름을 담을 배열들을 동적으로 할당한다. 그리고 각각의 점수와 이름들을 입력받고, 각각의 총점과 평균점수를 출력해주고 할당된 메모리를 해제해주는 코드이다. #include <stdio.h> #include <stdlib.h> #include <string.h> int get_student_num(); int alloc_students_scores(int num_student, int** ppscore_kor, int** ppscore_eng, int** ppscore_math                                 , int** ppscore_total); char** alloc_students_name(int num_student); void input_students_info(int num_student, int* pscore_kor, int* pscore_eng, int* pscore_math,                         int* pscore_total,  char **ppstudent_name); void print_avg(int num_student, int* pscore_total, char** ppstudent_name); void print_avgPerSub_totalAvg(int num_student,int* pscore_kor, int* pscore_eng, int* pscore_math, int* pscore_total); void freeMemory(int num_student,int* pscore_ko...