20210216_JavaScript07 Array_quiz확인, String methods, Array methods, JOSN개념(HTTP, AJAX, XMLHttpRequest, JSON, XML), JSON활용

14 분 소요

JavaScript07

  • JavaScript에 대해 공부하기 위해서 유튜브 ‘드림코딩by엘리’ JavaScript 강의를 듣고 글을 쓰고 있다.(강의가 엄청 잘되 있으니 강의를 찾아보자!)



드림코딩 Array_quiz (강의 듣고서 확인)

  • 일단, 강의 들으면서 놓친 Array API 위치를 확인함
  • 가독성 좋게 메소드를 연달아 쓸수 있는 법을 확인함(리얼 꿀팁)


'use strict';

// Q1. make a string out of an array
console.log(' Q1. make a string out of an array')
{
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.toString()); // apple,banana,orange
console.log(fruits.join());
console.log(fruits.join('|'));
const k = false
console.log(typeof(k))
console.log(k.toString())
}




console.log('')
console.log('Q2. make an array out of a string')
// Q2. make an array out of a string
{
const fruits = '🍎,🥝,🍌,🍒'
console.log(fruits.split(','))
}




console.log('')
console.log('Q3. make this array look like this : [5, 4, 3, 2, 1]')
// Q3. make this array look like this : [5, 4, 3, 2, 1]
{
const array = [1, 2, 3, 4, 5];
console.log(array.reverse()); // reverse 접근만 해도 영향을 줌
console.log(array);
}




console.log('')
console.log('Q4. make new array without the first two elements (변형하면 안됨)')
// Q4. make new array without the first two elements (변형하면 안됨)
{
// 변형 하는 경우
const array = [1, 2, 3, 4, 5];
array.splice(0, 2)
console.log(array)
const array1 = [1, 2, 3, 4, 5];
array1.shift();
array1.shift();
console.log(array1);
// 변형 안하는 경우
const array3 = [1, 2, 3, 4, 5];
console.log(array3.slice(2))
console.log(array3.slice(2, 5)) // slice에서 end index는 배제됨
console.log(array3)
}

class Student {
    constructor(name, age, enrolled, score) {
        this.name = name;
        this.age = age;
        this.enrolled = enrolled;
        this.score = score;
    }
}
const students = [
    new Student('A', 29, true, 45),
    new Student('B', 28, false, 80),
    new Student('C', 30, true, 90),
    new Student('D', 40, false, 66),
    new Student('E', 18, true, 88),
    // new Student('F', 30, true, 90), // filter 확인용
];





console.log('')
console.log('Q5. find a student with the score 90')
// Q5. find a student with the score 90
{ // 내가 한거 // filter 은 모두 찾아서 Array 만듦
const scores = students.filter((Student) => Student.score === 90);
// console.log(scoreSt);
console.log(scores.pop());
}
{ // 강의에서 한거 // find는 처음 찾은 것을 return
const score90 = students.find((Student) => Student.score === 90);
console.log(score90);
}




console.log('')
console.log('Q6. make an array of enrolled students')
// Q6. make an array of enrolled students
{
const enrolled = students.filter((Student) => Student.enrolled == true);
console.log(enrolled);
// console.log(students); // 원본 지장 없음
}




console.log('')
console.log("Q7. make an array containing only the students' scores")
// Q7. make an array containing only the students' scores
// result should be : [45, 80, 90, 66, 88]
{
const scores = students.map((Student) => Student.score);
console.log(scores);
// console.log(students) // 원본 지장 없음
}




console.log('')
console.log("Q.8 check if there is a student with the score lower than 50")
// Q.8 check if there is a student with the score lower than 50
{ // 내가 한거
const check = students.some((Student) => Student.score < 50);
console.log(check);
}
{ // 강의에서 한거 (and로 or 연산하고 싶으면 조건 반대로 하고 출력값도 반대로)
const check = !students.every((Student) => Student.score >= 50);
console.log(check);
}




console.log('')
console.log("Q.9 compute students' average score")
// Q.9 compute students' average score
{ // 내가 한거 (map, reduce) reduce는 피보나치 수열임
const scores = students.map((Student) => Student.score);
const average = scores.reduce((prev, curr) => {
    return (prev+curr)
}) / scores.length;
console.log(average);
}

{ // 내가한거 (map , for of loop)
const scores = students.map((Student) => Student.score);
let sum = 0;
for (let score of scores) {
    sum += score; 
};
const average = sum / scores.length
console.log(average)
}

{ // 강의 (reduce) // 첫번째 값 param 위치 조심! reduce(func, initial)
const average = students.reduce((prev, curr) => {
    return (prev+curr.score)
}, 0) / (students.length)
console.log(average);
}





console.log('')
console.log('Q.10 make a string containing all the scores')
// Q.10 make a string containing all the scores
// result should be : '45, 80, 90, 66, 88'
{
const scores = students.map((Student) => Student.score);
console.log(scores.join())
}





// Bonus! do Q10 sorted in asending order
console.log('')
console.log('Bonus! do Q10 sorted in asending order')
// result should be : '45, 66, 80, 88, 90'

{ // 내가 한거 // 결과 음수 a가 앞으로감 
// sort 만으로
const scores = students.map((Student) => Student.score);
const sort_scores = scores.sort((a, b) => {
    return a - b;
}); 
console.log(sort_scores.join())
}

{ // sort, if 이용해서
const scores = students.map((Student) => Student.score);
const sort_scores = scores.sort((a, b) => {
    if (a < b) {
        return -1;
    } else if (a > b) {
        return +1;
    } else {
        return 0;
    }
}); 
console.log(sort_scores.join())
}

{// 강의 (코드 가독성 굳굳 리얼)
const result = students
    .map((student) => student.score)
    .sort((a, b) => a - b)
    .join();
console.log(result);
}




ES String method

  • 강의에서 보니 정의된 위치를 찾아 갈때 어제는 symbol을 찾아 갔었던 것이다.. 다시보니 선택지가 두가지가 뜨는 것을 확인하고 다시 string method를 확인하고자 한다.


  • toString(): string;
    Array 때 처럼 똑같이 string형으로 바꾸어줌 (array, number, boolean 등 -> string)
  • charAt(pos: number): string;
    string에서의 특정 index를 param로 받아 해당 index의 character를 반환함
  • charCodeAt(index: number): number;
    특정 index를 받아 해당 index의 string character의 유니코드 값을 반환함 (해당 인덱스에 character가 없으면 NaN을 반환)
  • concat(...strings: string[]): string;
    해당 string 끝에 붙일 string들을 받아 합쳐 합친 것을 반환함
  • indexOf(searchString: string, position?: number): number;
    Array 때 처럼 찾고자하는 string 과 찾기 시작하는 index를 받아 시작하는 index로 부터 오르쪽으로 처음으로 발견한 인덱스를 반환
  • lastIndexOf(searchString: string, position?: number): number;
    indesOf와 같이 string 과 찾기 시작하는 index를 받아 시작하는 index로 부터 왼쪽으로 처음으로 발견한 인덱스를 반환
  • localeCompare(that: string): number;
    로케일 상의 문자열 정렬 순서에서 특정 string을 받아 원래의 string과 비교하여 순서를 알게 숫자를 반환(음수:참조문자,비교문자 순 / 양수 : 비교문자,참조문자 순서 / 0 : 둘이 같음)
  • replace(searchValue: string | RegExp, replaceValue: string): string;
    해당 string에서 찾는 문자와 대체할 문자를 param으로 받아 대체함
  • replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;
    해당 string에서 찾는 문자에 대체할 문자로 replacer라는 함수로 해당 string을 받아 활용해 return시킨 string으로 대체하게 할수 있다.
  • slice(start?: number, end?: number): string;
    해당 string의 부분을 반환 (start index 이상 end index 미만 까지 추출, end 없으면 마지막 index로 들어감) 항상 start index < end index 해야 함 만약 커버리면 ““를 반환, 음수 값도 음수 인덱스로 처리해서 인식
  • split(separator: string | RegExp, limit?: number): string[];
    separator로 특정 문자를 받아서 separator 문자를 기준으로 잘라서 배열의 원소로 만들어 배열을 만들음 limit은 배열로 들어갈 원소의 개수 제한임
  • substring(start: number, end?: number): string;
    slice와 똑같으나 start index > end index 여도 알아서 큰숫자를 end로 작은 숫자를 start로 인식함, 음수 인덱스는 무조건 0인덱스로 인식
  • toLowerCase(): string;
    소문자로 모두 변경
  • toUpperCase(): string;
    대문자로 모두 변경
  • toLocaleLowerCase(locales?: string | string[]): string;
    호스트의 현재 지정하고자 하는 로케일 옵션을 받아 소문자로 변경하고 로케일 값을 같이 가지고 있음
  • toLocaleUpperCase(locales?: string | string[]): string;
    위와 같은데 대문자로 변경
  • trim(): string;
    해당 string에서의 빈공백, 종결기호 등을 제거함 (데이터 정제시 좋다.)




interface String {
    /** Returns a string representation of a string. */
    toString(): string;

    /**
     * Returns the character at the specified index.
     * @param pos The zero-based index of the desired character.
     */
    charAt(pos: number): string;

    /**
     * Returns the Unicode value of the character at the specified location.
     * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.
     */
    charCodeAt(index: number): number;

    /**
     * Returns a string that contains the concatenation of two or more strings.
     * @param strings The strings to append to the end of the string.
     */
    concat(...strings: string[]): string;

    /**
     * Returns the position of the first occurrence of a substring.
     * @param searchString The substring to search for in the string
     * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.
     */
    indexOf(searchString: string, position?: number): number;

    /**
     * Returns the last occurrence of a substring in the string.
     * @param searchString The substring to search for.
     * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.
     */
    lastIndexOf(searchString: string, position?: number): number;

    /**
     * Determines whether two strings are equivalent in the current locale.
     * @param that String to compare to target string
     */
    localeCompare(that: string): number;

    /**
     * Matches a string with a regular expression, and returns an array containing the results of that search.
     * @param regexp A variable name or string literal containing the regular expression pattern and flags.
     */
    match(regexp: string | RegExp): RegExpMatchArray | null;

    /**
     * Replaces text in a string, using a regular expression or search string.
     * @param searchValue A string to search for.
     * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
     */
    replace(searchValue: string | RegExp, replaceValue: string): string;

    /**
     * Replaces text in a string, using a regular expression or search string.
     * @param searchValue A string to search for.
     * @param replacer A function that returns the replacement text.
     */
    replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;

    /**
     * Finds the first substring match in a regular expression search.
     * @param regexp The regular expression pattern and applicable flags.
     */
    search(regexp: string | RegExp): number;

    /**
     * Returns a section of a string.
     * @param start The index to the beginning of the specified portion of stringObj.
     * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.
     * If this value is not specified, the substring continues to the end of stringObj.
     */
    slice(start?: number, end?: number): string;

    /**
     * Split a string into substrings using the specified separator and return them as an array.
     * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.
     * @param limit A value used to limit the number of elements returned in the array.
     */
    split(separator: string | RegExp, limit?: number): string[];

    /**
     * Returns the substring at the specified location within a String object.
     * @param start The zero-based index number indicating the beginning of the substring.
     * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.
     * If end is omitted, the characters from start through the end of the original string are returned.
     */
    substring(start: number, end?: number): string;

    /** Converts all the alphabetic characters in a string to lowercase. */
    toLowerCase(): string;

    /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */
    toLocaleLowerCase(locales?: string | string[]): string;

    /** Converts all the alphabetic characters in a string to uppercase. */
    toUpperCase(): string;

    /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */
    toLocaleUpperCase(locales?: string | string[]): string;

    /** Removes the leading and trailing white space and line terminator characters from a string. */
    trim(): string;

    /** Returns the length of a String object. */
    readonly length: number;

    // IE extensions
    /**
     * Gets a substring beginning at the specified location and having the specified length.
     * @param from The starting position of the desired substring. The index of the first character in the string is zero.
     * @param length The number of characters to include in the returned substring.
     */
    substr(from: number, length?: number): string;

    /** Returns the primitive value of the specified object. */
    valueOf(): string;

    readonly [index: number]: string;
}




전글에서 놓쳤던 Array API

  • find,(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
    해당 Array의 value, index, obj를 활용하는 predicate 함수 조건에 배열의 원소가 처음으로 true 값을 가지는 경우 그 원소의 값을 반환(즉, 찾아서 처음 값), 없으면 undifined 반환 (thisArg는 함수에서 사용할 this로 사용할 객체)
  • findIndex, (predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
    find처럼 쓰이는데 찾은 첫번째 원소의 index값 반환
  • fill,(value: T, start?: number, end?: number): this;
    start index 이상 end index 미만 까지 value로 바꿔 채움(음수 인덱스 인식함)
  • copyWithin, (target: number, start: number, end?: number): this;
    start index 이상 end index 미만 까지의 원소를 복사하여 target index부터 차례대로 덮어씀
interface Array<T> {
    /**
     * Returns the value of the first element in the array where predicate is true, and undefined
     * otherwise.
     * @param predicate find calls predicate once for each element of the array, in ascending
     * order, until it finds one where predicate returns true. If such an element is found, find
     * immediately returns that element value. Otherwise, find returns undefined.
     * @param thisArg If provided, it will be used as the this value for each invocation of
     * predicate. If it is not provided, undefined is used instead.
     */
    find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
    find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;

    /**
     * Returns the index of the first element in the array where predicate is true, and -1
     * otherwise.
     * @param predicate find calls predicate once for each element of the array, in ascending
     * order, until it finds one where predicate returns true. If such an element is found,
     * findIndex immediately returns that element index. Otherwise, findIndex returns -1.
     * @param thisArg If provided, it will be used as the this value for each invocation of
     * predicate. If it is not provided, undefined is used instead.
     */
    findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;

    /**
     * Returns the this object after filling the section identified by start and end with value
     * @param value value to fill array section with
     * @param start index to start filling the array at. If start is negative, it is treated as
     * length+start where length is the length of the array.
     * @param end index to stop filling the array at. If end is negative, it is treated as
     * length+end.
     */
    fill(value: T, start?: number, end?: number): this;

    /**
     * Returns the this object after copying a section of the array identified by start and end
     * to the same array starting at position target
     * @param target If target is negative, it is treated as length+target where length is the
     * length of the array.
     * @param start If start is negative, it is treated as length+start. If end is negative, it
     * is treated as length+end.
     * @param end If not specified, length of the this object is used as its default value.
     */
    copyWithin(target: number, start: number, end?: number): this;
}




JavaScript - JSON

  • HTTP : client(request) <-> server(response) 끼리 통신하는 법으로 protocal 중의 하나 (Hypertext Transfer Protocal)
    • Hyptertext : web에서의 link, resource, docs, image, file 등
  • 통신 방법 2가지
    • fetch API
    • XHR((XMLHttpRequest) 객체를 사용하는 방법
  • AJAX : HTTP를 이용한 문서들을 받아오는 방법으로 web page에서 동적으로 서버에게 XHR 객체 형태로 데이터를 주고 받을 수 있는 기술 (Asynchronous JavaScript And XML)
    • XHR (XMLHttpRequest) : 브라우저 API에서 제공하는 오브젝트로 간단히 데이터를 서버에 요청하고 받아 올수 있음 ! XML 만 주고 받는게 아님(JSON, XML, HTML 그리고 일반 텍스트 형식 등을 포함한 다양한 포맷) !
  • XML : HTML처럼 markup 언어중에 하나로 과거에 주로 사용 (불필요한 태그가 많아, 가독성 떨어짐)
  • JSON (JavaScript Object Notation): Object {key : value} 이런 형식의 데이터 포맷
    • 브라우저 또는 모바일에서 서버와 데이터를 주고 받을 경우 사용
    • 서버 통신 하지 않을 경우 오브젝트를 file 시스템에 저장시에도 사용됨
    • simple data interchange format
    • lightweight text-based structure
    • easy to read
    • key-value pairs
    • used for serialization and transmission of data between the network the network connection (데이터 직렬화 및 전송시 쓰임)
    • independent programming language and platform (프로그램 언어에 상관 없이 같이 사용가능)




JSON 공부 방법

  • object를 어떻게 serialize 하여 json(string)으로 변환 할지
  • 반대로 json을 deserialize 하여 object로 변환 할지
interface JSON {
    /**
     * Converts a JavaScript Object Notation (JSON) string into an object.
     * @param text A valid JSON string.
     * @param reviver A function that transforms the results. This function is called for each member of the object.
     * If a member contains nested objects, the nested objects are transformed before the parent object is.
     */
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
    /**
     * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
     * @param value A JavaScript value, usually an object or array, to be converted.
     * @param replacer A function that transforms the results.
     * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
     */
    stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
    /**
     * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
     * @param value A JavaScript value, usually an object or array, to be converted.
     * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
     * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
     */
    stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}




JSON 관련 사이트

  • JSON Diff
    • 서버에서 받아온 자료가 첫번째와 두번째 자료가 어떻게 다른지 모를때 비교 가능
    • 문제 debuging 시에 사용 가능
  • JSON Beautifier
    • 서버에서 받아온 JSON 포멧이 망가지는 경우(코드를 그냥 줄글로 가져와 진경우) -> 포맷 형태로 만들어줌
  • JSON Parser
    • json을 object형태로 확인 하고 싶다면 사용(눈으로 쉽게 확인 가능)
  • JSON Validator
    • JSON syntax 확인 가능