티스토리 뷰

한번으론 이해가 안돼네 ㅋㅋㅋ

이해할때까지 보면 돼!

나는!!! 이럴꺼면 시작도 안했어!

이번건 강의만으로는 이해 못해서 다시 하나씩 찾아보면서 공부할 예정이다.

 

총 10개의 array api로 구성된다.

이번 강의는 하나씩 문제로 되어있었고 ctrl을 이용해 라이브러리를 확인해가며 설명해주셨다.

 

1. 배열에서 문자열 꺼내기

// 01. make a string out of array
{
    const fruits = ['apple','banana','orange'];
}

join( )이라는 함수를 이용한다!

    /**
     * Adds all the elements of an array into a string, separated by the specified separator string.
     * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.
     */
    join(separator?: string): string;

최첨단 시대에 사는 우리는 번역기라는 갓갓능력을 컴퓨터만 있으면 가질수있다!

 * 배열의 모든 요소를 ​​지정된 구분 기호 문자열로 구분하여 문자열에 추가합니다.
     * @param separator 배열의 한 요소를 결과 문자열의 다음 요소와 구분하는 데 사용되는 문자열입니다. 생략하면 배열 요소가 쉼표로 구분됩니다.

조인이라는 곳에 세퍼레이터를 넣어도 되고 안 넣어도 되는데

이는 문자열로 구분하여 문자열에 추가한다고 한다

이해가 안돼면 해보면 된다.!!!

join 안에 아무것도 넣지 않았을때는 apple,banana,orange 이런 식으로 출력된다.

물결을 괄호 안에 넣었더니 apple~banana~orange 이렇게 출력되었다

 

join은 이런식으로 안에 구분할수있게 문자열을 넣어줘 하나의 문자열로 만들어주는 친구이다.

 

2. 배열로 만들기

// 02. make an array out out of a string
{
    const fruits = 'a,b,c,d';
}

split() 을 이용하면 되는데 이는 무엇인가 하니

    /**
     * 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[];
  * 지정된 구분 기호를 사용하여 문자열을 부분 문자열로 분할하고 배열로 반환합니다.
     * @param separator 문자열을 구분하는 데 사용할 문자를 식별하는 문자열입니다. 생략하면 전체 문자열을 포함하는 단일 요소 배열이 반환됩니다.
     * @param limit 배열에 반환되는 요소의 수를 제한하는 데 사용되는 값입니다.

split 안에 세퍼레이터를 문자열을 넣는데 이를통해 구분한다고 한다 근데 제한을 해도 되고 안해도 되는데

limit값을 결정할 수 있다.

이건 ','이렇게 하게 될경우 a b c d를 각각 배열에 넣어주는 함수이다. ['a','b','c','d']로 나온다

// 02. make an array out out of a string
{
    const fruits = 'a,b,c,d';
    const result = fruits.split(',');
    console.log(result);
}

만약 구분자를 안 넣게 되면 하나로 합쳐져서 한 칸에 들어가는 모습을 보인다. 이런식으로 ['a,b,c,d']

3. 거꾸로 배열 만들기

// 03. make this array look like this: [5,4,3,2,1]
{
    const array = [1,2,3,4,5];
}

reverse()를 이용하면 배열이 역순으로 배치되는데

// 03. make this array look like this: [5,4,3,2,1]
{
    const array = [1,2,3,4,5];
    const result = array.reverse();
    console.log(result);
    console.log(array);
}

[5, 4, 3, 2, 1]

[5, 4, 3, 2, 1]

의 결과가 나온다

이는 즉 result 넣는 새로운 배열만이 아니라 애초에 array의 배열이 역순으로 변경되어 담기는 거라는 점을 명심해야된다.

4. 1번 2번 요소없이 배열 새로 만들기

//04. make new array without the first two elements
{
    const array = [1,2,3,4,5];
}

splice()를 기억하는가? 지난 번 수업에 있던 내용인데 이는

어디 인덱스부터 몇개 지울건지를 해주는 함수인데 이는 새로 배열을 만들어주지 않는다

우리는 새로운 배열이 필요하다구!

 

slice()를 이용하면 된다.

/**
     * Returns a copy of a section of an array.
     * For both start and end, a negative index can be used to indicate an offset from the end of the array.
     * For example, -2 refers to the second to last element of the array.
     * @param start The beginning index of the specified portion of the array.
     * If start is undefined, then the slice begins at index 0.
     * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.
     * If end is undefined, then the slice extends to the end of the array.
     */
    slice(start?: number, end?: number): T[];
* 배열 섹션의 복사본을 반환합니다.
     * 시작과 끝 모두에 대해 음수 인덱스를 사용하여 배열 끝에서 오프셋을 나타낼 수 있습니다.
     * 예를 들어 -2는 배열의 마지막에서 두 번째 요소를 나타냅니다.
     * @param start 배열의 지정된 부분의 시작 인덱스입니다.
     * start가 정의되지 않은 경우 슬라이스는 인덱스 0에서 시작합니다.
     * @param end 배열의 지정된 부분의 끝 인덱스입니다. 이것은 인덱스 '끝'에 있는 요소를 제외합니다.
     * end가 정의되지 않은 경우 슬라이스는 배열의 끝까지 확장됩니다.

0부터 2까지라고 지정하면 0과 1만 전달된다는 점을 명심한다!

//04. make new array without the first two elements
{
    const array = [1,2,3,4,5];
    //const result = array.splice(0,2); // 0부터 2개를 삭제하겠다/ 어디서부터 몇개지울지
    const result = array.slice(2,5); 
    console.log(result);
}

로 하면 된당!


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),
};

여기서부터는 위 내용을 이용하여 해결한다.

5. 90점인 학생 찾기

// 05. find a student with the score 90
{
}
// 05. find a student with the score 90
{
    const result = student.find((student) => student.score === 90);
    console.log(result);
}

find 함수는 내부를 콜백하여 매칸마다 함수를 적용시킨다.

우리가 배열에 요소마다 호출이 되서 각각 학생의 점수가 90점이면 true를 리턴하고

find는 첫번째로 true가 나오면 이를 내보내준다

 

6. 등록된 학생 찾기 

// 06. make an array of enrolled students
{
}
// 06. make an array of enrolled students
{
    const result = students.filter((students) => student.enrolled);
    console.log(result);
}

filter()은 수업에 등록된 학생만 받고 싶을때 사용

enrolled가 true일때 이것만 전달해서 새로운 배열로 만들어준다.

a c e 학생의 배열이 만들어진다.

우리가 원하는 것만 받아올수있음!

7.  학생 점수만 받아서 배열 만들기

// 07. make an array containing only the students' scores
// result should be: [45,80,90,66,88]
{
}

map() 은 지정된 배열 안 요소들이 콜백함수를 걸쳐서

각각 새로운 배열에 담기는 함수이다.

// 07. make an array containing only the students' scores
// result should be: [45,80,90,66,88]
{
    const result = students.map((student)=>student.score*2);
    console.log(result);
}

이러면 배열안에 점수들은 2배가 되어 담겨진다. ['90','160','180','132','176'] 이런식으로 말이다.

이런식으로 map()을 이용하여 해결해보면

그냥 *2만 지우면 된다 ㅋㅋㅋ...

 

많은 사람들이 콜백함수 내부에서 의미없는 이름을 지어서 사용할때가 있는데 student를 사용한 것처럼

모르는 사람이 봤을때 이해하기 쉬운 단어를 선택하는 것이 좋다.

 

8. 50점 미만인 학생 있는지 확인

// 08. check if there is a student with the score lower than 50
{
}

some()을 이용하면 되는데 이는 콜백함수가 리턴이 트루가 되는 애가 있는지 없는지를 확인해준다.

// 08. check if there is a student with the score lower than 50
{
    const result = students.some((student)=>student.score<50);
    console.log(result);
}

요소 하나하나마다 수행이 되는데 배열에서 하나라도 true가 있으면 true가 된다(비교연산자에서 or이랑 비슷한 느낌)

반대로 그럼 전부 true일때 true를 출력하는 애는 

every()라고 있다(and랑 비슷함 ㅋㅋ)

이렇게 외우면 쉬울 것 같다

9. 학생 평균 구하기

// 09. compute students' average score
{
}

reduce()라는 것을 이용하면 되는데

이는 우리가 콜백함수를 전달하고 또는 이니셜 벨류를 전달하게 되는데

//

콜백함수는 배열안에 들어있는 모든 요소들마다 호출이 되는데 리턴되는 값은 함께 누적된 결과값을 리턴함

누적되어 전달해야되는구나 라고 알면 됨(모아놓을때 쓰는거라고 생각하면 됨)

//

 

강의 내용은 이해 안됐는데 찾아보니

map은 변형해서 다시 배열을 만든다면

reduce는 변형해서 배열을 만들던지 하나의 값을 도출하던지 할수있는애라고 생각하라 했음

 

이것은 리턴 값을 해줘야됨...

// 09. compute students' average score
{
    const result = students.reduce((prev,curr) => {
    console.log('--------------');
    console.log(prev);
    console.log(curr);
    });
}

이럼 undefined뜨는데 그 이유는 리턴 안해줘서임

// 09. compute students' average score
{
    const result = students.reduce((prev,curr) => {
    console.log('--------------');
    console.log(prev);
    console.log(curr);
    return curr;
    });
}

이제 리턴해주면

어떻게 되냐면

curr을 리턴했잖음 이게 prev로 들어감 

이제 해결해보자면

// 09. compute students' average score
{
    const result = students.reduce((prev,curr) => {
    console.log('--------------');
    console.log(prev);
    console.log(curr);
    return prev + curr.score;
    }, 0); //0을 쓰면 이제 a부터 시작이아니라 0부터시작함
}

이렇게 하면됨

그러면 점수가 prev로 들어가게 되고 0부터 시작해서 차곡차곡쌓임

10.  모든 점수가 들어가있는 문자열 구하기

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

위에서 배운 것을 합쳐서 하는데 학생의 점수를 map으로 가져와서 join하면 된다.

 

오늘꺼는 좀 어렵고 시간도 굉장히 오래걸렸는데 확실히 내꺼 만들기 전까지는 다음 꺼 안 넘어가야겠다.

알고리즘 같은 거 할 생각하면 초반에 잘 길들여놔야될듯 ㅠㅠ

이제 슬슬 어려워진다...홧팅,!