20210215_JavaScript06 ES Array API(methods), String methods, 드림코딩Array_quiz

15 분 소요

JavaScript06

  • JavaScript에 대해 공부하기 위해서 유튜브 ‘드림코딩by엘리’ JavaScript 강의를 듣고 글을 쓰고 있다.

ES Symbol String method

interface String {
    /**
     * Matches a string or an object that supports being matched against, and returns an array
     * containing the results of that search, or null if no matches are found.
     * @param matcher An object that supports being matched against.
     */
    match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;

    /**
     * Replaces text in a string, using an object that supports replacement within a string.
     * @param searchValue A object can search for and replace matches within a string.
     * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
     */
    replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;

    /**
     * Replaces text in a string, using an object that supports replacement within a string.
     * @param searchValue A object can search for and replace matches within a string.
     * @param replacer A function that returns the replacement text.
     */
    replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;

    /**
     * Finds the first substring match in a regular expression search.
     * @param searcher An object which supports searching within a string.
     */
    search(searcher: { [Symbol.search](string: string): number; }): number;

    /**
     * Split a string into substrings using the specified separator and return them as an array.
     * @param splitter An object that can split a string.
     * @param limit A value used to limit the number of elements returned in the array.
     */
    split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}



ES Array API (정의된 위치에서 본 API)

  • ES Array API 선언된 위치에서 내용 확인해보기

  • length : Array안의 요소 개수 보여줌 (read only)
  • toString(): string;
    • : Array 안의 요소들을 string으로 표현(구분자 : ,)
  • toLocaleString(): string;
    • : toString처럼 쓰이지만 locale(날짜, 시간, 달력, 소수점, 환율 등 여러가지 요소를 국가에 맞게)법칙에 맞게 표현


  • concat (...items: (T | ConcatArray<T>)[]): T[];
    • : 다른 배열들을 param으로 받아 끝에다 붙여 합침
  • join (separator?: string): string;
    • : string인 구분자를 param으로 받아 배열의 구분자를 수정함(param 없으면 기본 ,가 구분자임)
  • slice (start?: number, end?: number): T[];
    • : 요소의 index번호의 start, end를 숫자형태(number)로 param 으로 받아 start이상~end 미만 요소만 구성하여 배열 반환


  • indexOf (searchElement: T, fromIndex?: number): number;
    • : 찾을 요소의 값을 받고, 찾기 시작할 인덱스 넘버를 받아서 지정한 인덱스 요소 부터 시작하여 찾아 첫번째로 발견되는 값의 절대 인덱스를 리턴 (fromIndex param을 빠뜨리면 기본 인덱스 0으로 설정)
  • lastIndexOf (searchElement: T, fromIndex?: number): number;
    • : indexOf와 같은데 찾는 것을 왼쪽으로 시작함(역순으로), 그래서 처음으로 찾은 값의 절대 인덱스를 리턴(fromIndex도 절대 인덱스, 찾아서 리턴하는 인덱스도 절대 인덱스임 포인트는 찾는 순서가 왼쪽으로 흘러가서 처음 만나는 것이라는 거!, from Inex없으면 마지막 요소를 시작해서 찾음) !! 값이 없으면 index, lastindex모두 -1 리턴
const raccoon1 = ['tom', 'jerry', 'snoopy', 'micky', 'miny', 'snoopy']
console.log(raccoon1.lastIndexOf('snoopy')) //5
console.log(raccoon1.lastIndexOf('snoopy', 0)) // -1
console.log(raccoon1.lastIndexOf('snoopy', 1)) // -1
console.log(raccoon1.lastIndexOf('snoopy', 2)) // 2
console.log(raccoon1.lastIndexOf('snoopy', 3)) // 2
console.log(raccoon1.lastIndexOf('snoopy', -1)) // 5
console.log(raccoon1.lastIndexOf('snoopy', -2)) // 2
console.log(raccoon1.lastIndexOf('snoopy', -3)) // 2
console.log(raccoon1.lastIndexOf('snoopy', -4)) // 2
console.log(raccoon1.lastIndexOf('snoopy', -5)) // -1


  • every (predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
    • : every의 경우 Array의 value, index, array를 param으로 받아 every 안에서 함수를 선언하여 그 함수 조건에서 배열의 요소를 순환하여 모두 true일 경우 true를 리턴하고 그외에는 false를 반환함(즉 ,배열에서 and 조건임) thisArg param은 선택으로서 predicate를 지칭할 수 있는 문자 설정
  • some some(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
    • : some은 every처럼 똑같이 함수 조건에서 배열의 요소를 순환하는데 몇개만 true여도 true 리턴 ( 즉, 배열 or 조건임)


  • forEach (callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void;
    • : forEach는 param으로 배열의 value, index, array를 받아 callback함수를 구성하여 배열의 요소를 순환하면서 해당 함수의 코드를 return한다.
  • map <U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[];
    • : 배열에서의 value, index, array를 param으로 하는 callback 함수의 결과값을 묶어 배열로 return 함
  • filter (predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[];
    • : 배열에서의 value, index, array를 통한 조건함수를 구성하여 조건에 만족하는 요소만 모아 배열로 return


  • reduce (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T; : reduce는 배열의 previousValue(accumulator, currentValue, currentIndex, array를 param으로 받아 함수를 구성하여 연산시킴 (피보나치 수열처럼 전 계산된 이전 값을 연산축적하면서 계산되어 최종적으로 배열의 원소들이 연산되어 1개의 값을 가지게 됨, 연쇄 계산) initialValue는 연산될 초기 currentValue를 설정 할 수 있음
  • reduceRight (callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T; : reduce와 같은데 연산 방향이 배열의 오른쪽(마지막)에서 시작하여 거꾸로 연산


  • readonly가 없는 경우(원본에 지장을 주는 경우)
  • pop(): T | undefined;
    • : 배열에서 마지막 요소를 없애고, 없앤 요소를 return
  • push (...items: T[]): number;
    • : 배열에 새로운 원소들을 추가하고 추가한 원소의 개수를 return


  • sort (compareFn?: (a: T, b: T) => number): this;
    • : a , b를 사용해서 비교 함수식을 만들어 배열의 원소끼리 비교함수식에 연산하여 음수가 나오면 a 가 앞으로 나오고, 양수가 나오면 b가 앞으로 나옴, 0 이면 바꾸지 않음 (compareFunction이 없으면 유니코드 포인트로 순서 정함)
  • reverse(): T[];
    • : 배열의 원소들의 순서를 거꾸로함


  • shift(): T | undefined;
    • : 배열에서 첫번째 요소를 없애고, 없앤 요소를 return함
  • unshift (...items: T[]): number;
    • : 배열에 새로운 요소들을 앞에서 추가함


  • splice (start: number, deleteCount: number, ...items: T[]): T[];
    • : 지정한 start index number에서 시작하여 deleteCount(지울 개수)만큼 지우고 items에 원소들을 그 자리에 넣음, 그리고 지운 원소들을 return함


/////////////////////////////
/// ECMAScript Array API (specially handled by compiler)
/////////////////////////////

interface Array<T> {
    /**
     * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
     */
    length: number;
    /**
     * Returns a string representation of an array.
     */
    toString(): string;
    /**
     * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.
     */
    toLocaleString(): string;
    /**
     * Removes the last element from an array and returns it.
     */
    pop(): T | undefined;
    /**
     * Appends new elements to an array, and returns the new length of the array.
     * @param items New elements of the Array.
     */
    push(...items: T[]): number;
    /**
     * Combines two or more arrays.
     * @param items Additional items to add to the end of array1.
     */
    concat(...items: ConcatArray<T>[]): T[];
    /**
     * Combines two or more arrays.
     * @param items Additional items to add to the end of array1.
     */
    concat(...items: (T | ConcatArray<T>)[]): T[];
    /**
     * Adds all the elements of an array separated by the specified separator string.
     * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
     */
    join(separator?: string): string;
    /**
     * Reverses the elements in an Array.
     */
    reverse(): T[];
    /**
     * Removes the first element from an array and returns it.
     */
    shift(): T | undefined;
    /**
     * Returns a section of an array.
     * @param start The beginning of the specified portion of the array.
     * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
     */
    slice(start?: number, end?: number): T[];
    /**
     * Sorts an array.
     * @param compareFn Function used to determine the order of the elements. It is expected to return
     * a negative value if first argument is less than second argument, zero if they're equal and a positive
     * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
     * ```ts
     * [11,2,22,1].sort((a, b) => a - b)
     * ```
     */
    sort(compareFn?: (a: T, b: T) => number): this;
    /**
     * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
     * @param start The zero-based location in the array from which to start removing elements.
     * @param deleteCount The number of elements to remove.
     */
    splice(start: number, deleteCount?: number): T[];
    /**
     * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
     * @param start The zero-based location in the array from which to start removing elements.
     * @param deleteCount The number of elements to remove.
     * @param items Elements to insert into the array in place of the deleted elements.
     */
    splice(start: number, deleteCount: number, ...items: T[]): T[];
    /**
     * Inserts new elements at the start of an array.
     * @param items  Elements to insert at the start of the Array.
     */
    unshift(...items: T[]): number;
    /**
     * Returns the index of the first occurrence of a value in an array.
     * @param searchElement The value to locate in the array.
     * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
     */
    indexOf(searchElement: T, fromIndex?: number): number;
    /**
     * Returns the index of the last occurrence of a specified value in an array.
     * @param searchElement The value to locate in the array.
     * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
     */
    lastIndexOf(searchElement: T, fromIndex?: number): number;
    /**
     * Determines whether all the members of an array satisfy the specified test.
     * @param predicate A function that accepts up to three arguments. The every method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value false, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
    every<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): this is S[];
    /**
     * Determines whether all the members of an array satisfy the specified test.
     * @param predicate A function that accepts up to three arguments. The every method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value false, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
    every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
    /**
     * Determines whether the specified callback function returns true for any element of an array.
     * @param predicate A function that accepts up to three arguments. The some method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value true, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
    some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
    /**
     * Performs the specified action for each element in an array.
     * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
     * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
    /**
     * Calls a defined callback function on each element of an array, and returns an array that contains the results.
     * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
    /**
     * Returns the elements of an array that meet the condition specified in a callback function.
     * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
     */
    filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
    /**
     * Returns the elements of an array that meet the condition specified in a callback function.
     * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
     */
    filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
    /**
     * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
     * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
     * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
     */
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
    /**
     * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
     * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
     * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
     */
    reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
    /**
     * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
     * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
     * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
     */
    reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
    reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
    /**
     * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
     * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
     * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
     */
    reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;



드림코딩 Array_quiz

  • 강의 안보고 일단 method 읽어 본것을 바탕으로 문제를 풀어봄
'use strict';

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

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

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

// Q4. make new array without the first two elements
{
const array = [1, 2, 3, 4, 5];
array.splice(0, 2)
console.log(array)
}

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

// Q5. find a student with the score 90
{
const scoreSt = students.filter((Student) => Student.score == 90);
console.log(scoreSt.pop());
}

// Q6. make an array of enrolled students
{
const enrolledSt = students.filter((Student) => Student.enrolled == true);
console.log(enrolledSt);
}

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

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

// Q.9 compute students' average score

{ // map, reduce 
const scores = students.map((Student) => Student.score);
const average = scores.reduce((a, b) => {
    return (a+b)
}) / scores.length;
console.log(average);
}

{ // 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)
}

// 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
// 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)
}

{ // 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)
}