Javascript6(Array) feat.Ellie&velopert

13856 ワード

Array
  • object
  • ウサギ(両耳、食べる、走る)&ニンジン(オレンジ、ビタミンc)
  • 相互に関連する特徴と行為を組み合わせた
  • 資料構造
  • 類似オブジェクト間の組合せ
  • 格子密集の資料構造
  • インデックス(0から)
  • が指定されています.
    1.Declaration(声明)
  • const arra1 = new Array();
  • cont arr2 = [1, 2];
  • 2. Index position
    const fruits = ['apple', 'banana'];
    console.log(fruits); // (2)['apple', 'banana'] , 배열로 출력
    console.log(fruits.length); // 2 , 배열의 길이 출력
    console.log(fruits[0]); // apple , 인덱스 번호가 맞는 배열의 값 출력
    console.log(fruits[1]); // banana , 인덱스 번호가 맞는 배열의 값 출력
    console.log(fruits[fruits.length-1]); // banana , 길이 - 1 => 1
    3. Looping over an array
    for(let i = 0; i < fruits.length; i++) {
    	console.log(fruits[i]);
    }
    
    for (let furit of fruits) {
    	console.log(furit);
    }
    
    // forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
    fruits.forEach(fruit => console.log(fruit));
    4. Additon, deletion, copy
    // push : add an item to the end
    fruits.push('strowberry', 'peach');
    console.log(fruits);
            
    // pop : remove an item from the end
    fruits.pop();
    console.log(fruits);
    
    // unshift : add an item to the benigging
    fruits.unshift('strowberry', 'peach');
    console.log(fruits);
    
    // shift : remove an item from the benigging
    fruits.shift();
    console.log(fruits);
    
    // note!! shift, unshift are slower than pop, push
    
    // splice : remove an item by index position
    fruits.push('strowberry', 'peach', 'lemon');
    console.log(fruits);
    // .splice(index); index로 부터 뒤에 있는 모든 요소 삭제
    fruits.splice(1);
    // .splice(index, deleteCount); index로 부터 몇개의 요소 삭제
    fruits.splice(1,1);
    // .splice(index, deleteCount, ...item); index로 부터 몇개의 요소 삭제 후 뒤에 아이템 추가
    fruits.splice(1,1, 'greenapple', 'waltermelon');
    
    // combine two arrays
    // 배열에 배열을 추가하여 새로운 배열을 반환
    const fruits2 = ['pear', 'coconut'];
    const newFruits = fruits.concat(fruits2);
    console.log(newFruits);
    5. Searcing
    // indexOf : find the index
    // 해당 요소의 index를 찾아주며 없으면 -1 반환
    console.log(fruits);
    console.log(fruits.indexOf('apple')); // 0
    console.log(fruits.indexOf('waltermelon')); // 2
    console.log(fruits.indexOf('kiwi')); // -1
    
    // includes
    // 배열 안에 해당 요소가 있는지 없는지 true / false를 반환
    console.log(fruits.includes('apple')); //true
    console.log(fruits.includes('kiwi')); // false
    
    // lastIndexOf
    fruits.push('apple');
    console.log(fruits);
    console.log(fruits.indexOf('apple')); 
    // 0, 배열안에 있는 해당 요소의 index를 찾아주는데 첫번째 요소만 찾고 반환
    console.log(fruits.lastIndexOf('apple')); 
    // 5, 배열안에 있는 해당 요소의 index를 찾아주는데 마지막 요소만 찾고 반환
    6.配列の組み込み関数
    const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
    const array = [1, 2, 3, 4, 5, ... 8];
    const todos = [
    		{
    			id : 1,
    			text : '자바스크립트 입문',
    			done : true
    		},
    		{
    			id : 2,
    			text : '함수 배우기',
    			done : true
    		},
    		{
    			id : 3,
    			text : '객체와 배열배우기',
    			done : true
    		},
    		{
    			id : 4,
    			text : '배열 내장함수 배우기',
    			done : flase
    		},
    	       ]
    const numbers = [10, 20, 30, 40];
    01.forEach()メソッド
  • 配列値を出力方法
  • // 반복문을 사용하는 방법
    for (let i = 0; i < superheroes; i++) {
    	console.log(superheroes[i]);
    }
    
    // forEach(함수)
    // 함수는 외부에 선언 후 작성해 줘도 된다
    function print(hero){
    	console.log(hero);
    }
    
    superheroes.forEach(print);
    
    superheroes.forEach(function(hero) {
    	console.log(hero)
    });
    
    superheroes.forEach(hero =></superheroes> {
    	console.log(hero)
    });
    02.map()メソッド
  • アレイの要素を別の形式に変換するために、新しいアレイ
  • に戻る.
    // 반복문을 통해서 값 변경
    const squared = [];
    for(let i = 0; i < array.length; i++) {
    	squared.push(array[i] * array[i]);
    }
    // forEach(함수) 사용
    const squared = [];
    array.forEach(n=> {
    	squared.push(n * n);
    })
               
    // map(함수) 사용
    const square = n => n * n; // arrow function
    const squared = array.map(square);
    const squared = array.map(n => n * n);
    
    // test
    const items = [
    		{
    			id : 1,
    			text : 'hello'
    		},
    		{
    			id : 2,
    			text : 'bye'
    		}
    	       ];
    
    const texts = items.map(item => item.text);
    03.indexOf()メソッド
  • 配列で必要なアイテムを検索する方法(配列値が整数、実数、文字列、ブール値の場合)
  • .
  • は、最初に見つかった値
  • を返します.
    // 배열.indexOf('찾는 값');
    const index = superheroes.indexOf('토르');
    04.findIndex()メソッド
  • 配列で必要なアイテムを検索する方法(値がオブジェクトまたは条件がインデックスの場合に使用)
  • .
  • は、最初に見つかった値
  • を返します.
  • 特定の条件をチェックし、条件が一致する要素の位置
  • を返す.
    // 배열.findIndex(조건);
    const index = todos.findIndex(todo => todo.id === 3);
    05.find()メソッド
  • は、見つかったオブジェクト自体または要素などの
  • を返す.
    // 배열.find(조건);
    const index = todos.find(todo => todo.done === false);
    06.フィルタ()方法
  • は、特定の条件を満たす要素を検索し、アレイ
  • に戻る.
    // 배열.filter(조건)
    const taskNotDone = todos.filter(todo => todo.done === false);
    const taskNotDone = todos.filter(todo => !todo.done);
    07.接合()方法
  • アレイから特定のアイテムを削除および削除する値
  • を返します.
    // 배열.splice(inidex, 제거할 갯수)
    const index = numbers.indexOf(30);
    numbers.splice(index,1);
    08.slice()メソッド
  • 配列から特定の項目を切り取って配列に戻るソースは影響を受けない
  • .
  • start indexからlast indexまでlast indexの値
  • は返されません.
    // 배열.slice(start index, end index)
    const sliced = numbers.slice(0,2);
    09.shif()メソッド
    アレイから
  • の最初の要素を抽出する、抽出値
  • をソースから削除する.
    // 배열.shift()
    const value = numbers.shift();
    10.pop()メソッド
    最後の要素
  • がアレイから抽出する、抽出された値
  • がソースから削除される.
    // 배열.shift()
    const value = numbers.shift();
    11.unshift()メソッド
  • push()メソッドのように値を追加し、一番前は
  • です.
    // 배열.unshift(추가할 원소)
    numbers.unshift(5);
    12.push()メソッド
  • unshift()メソッドのように値を追加します.後は
  • です.
    // 배열.push(추가할 원소)
    numbers.push(50);
    13.concat()メソッド
  • 複数のアレイを1つのアレイに結合して新しいアレイを作成します.元のアレイは
  • です.
    const arr1 = [1, 2, 3];
    const arr2 = [4, 5, 6];
    const concated = arr1.concat(arr2);
    // 스프레드 연산자로 concat 대처
    const concated = [...arr1, ...arr2];
    14.join()メソッド
  • 配列の値を文字列に生成し、
  • を返します.
    const array = [1, 2, 3, 4, 5];
    var arrStr1 = array.join();
    //separator(문자열로 만들 때 배열 값 구분 문자) 수정
    var arrStr2 = array.join(" ");
    var arrStr3 = array.join(", ");
    15.reduce()メソッド
  • 配列のすべての値を使用して演算する場合は
  • を使用します.
  • アキュムレータはアキュムレータ値、電流は元素
  • である.
  • indexは要素のindexであり、arrayは配列自体
  • である.
    // forEach문
    const numbers = [1, 2, 3, 4, 5];
    let sum = 0;
    numbers.forEach( n => {sum += n;})
    console.log(sum);
    
    // 배열.reduce((accumulator, current) => 연산, 초기accumulator값)
    const sum = numbers.reduce((accumulator, current) => accumulator + current, 0)
    console.log(sum)
    
    // 배열.reduce((accumulator, current, index, array) => 연산, 초기accumulator값)
    const avg = numbers.reduce((accumulator, current, index, array) => {
    			if (index === array.length - 1) {
    				return (accumulator + current) / array.length;
    			}
    			return accumulator + current;
    			}, 0)
    console.log(sum)
            
    // 배열안에 있는 각 알파벳의 갯수를 객체로 반환
    const alphabets = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e'];
    const count = alphabets.reduce((acc, current) => {
    			if (acc[current]) { <= acc.a
    				acc[current] += 1;
    			} else {
    				acc[current] =  1;
    			}
    			}, {}) <= 비어 있는 객체 
    Array Quiz
    01. make a string out of an array
    const fruits = ['apple', 'banana', 'orange'];
    
    // .join(separator?: string): string;
    // Adds all the elements of an array separated by the specified separator string.
    // 배열의 있는 모든 요소를 더해서 string으로 return을 하는데
    // 전달해준 separated를 문자열을 이용해서 구분자를 넣어서 반환해줘
    // seoarated는 전달해줘도 되고 안해줘도 된다
    
    const result = fruits.join();
    const result = fruits.join('and');
    02. make an array out of a string
    const fruits = 'apple, kiwi, banana, cherry';
    
    // .split(separtor: string | RefExp, limit? number) : string[];
    // Split a string into substrings using the specified separtor
    // 문자열을 전달해준 separotr을 기준으로 나누어 string array로 반환
    // limit 사이즈를 지정해줘도 되고 안해줘도 된다 .split(",",2)
    
    const result = fruits.spit(",");
    03. make this array look like this : [5,4,3,2,1]
    const array = [1,2,3,4,5];
    
    // Reverses the elements in an Array.
    // 기존의 배열에도 영향을 준다
    
    const resilt = array.reverse();
    04. make new array without the first tow elements
    const array = [1,2,3,4,5];
    
    // splice(start: number, deleteCount?: number): T[];
    // Removes elements from an array and,
    // if necessary, inserts new elements in their place, returning the deleted elements.
    // 지워진 값을 반환, 문제에 합당하지 않음
    
    // slice(start?: number, end?: number): T[];
    // Returns a section of an array.
    // @param end The end of the specified portion of the array.
    // This is exclusive of the element at the index 'end'.
    // 마지막 인덱스는 배제 되서 반환
    
    const result = array.slice(2);
    const result = array.slice(2, 5);
    05 ~ 10
    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),
    ]
    05. find a students with the score 90
    // find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
    // Returns the value of the first element in the array where predicate is true, and undefined
    // 첫번째로 찾아진 값을 리턴하는데 true일 때 return을 하고 없으면 undeifine가 반환된다
    
    const result = students.find(student => student.score === 90);
    06. make an array of enrolled students
    // 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.
    
    const resilt = students.filter(student => student.enrolled);
    07. make an array containing only the students scores
    result should be : [45, 80, 90, 66, 88]
    
    // map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
    // Calls a defined callback function on each element of an array, and returns an array that contains the results.
    
    const result = students.map(student => student.score);
    08. check if there is a student with the score lower than 50
    result false
        
    // some(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.
    // 배열의 요소 중에서 callback 함수가 true가 되는게 있는지 없는지 확인, true/ false로 반환
    
    const result = students.some(student => student.score < 50); // true
    
    // 배열에 있는 모든 요소들이 callbackFn에 만족을 하는지 확인, true/ false로 반환
    const result = students.every(student => student.score >= 50); //false
    09. compute students average score
    // 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.
    // 콜백 함수는 모든 요소마다 출력 되며 공통된 누적값을 리턴 된다
    
    const reuslt = students.reduce((prev, curr, index, array)=>{
    				if(index == array.length-1){
    					prev += curr.score;
    					return prev /= array.length;
    				}else{
    					return prev += curr.score;
    				}
    			       },0)
    10. make a string containing all the scores
    // result should be : '45, 80, 90, 66, 88'
    const result = students.map(student => student.score).join();
    11. sotred in ascending order
    // result should be : '45, 66, 80, 88, 90';
    // .sort((a,b)=>a-b), 작은값에서 큰값 정렬
    // a 는 이전값, b는 현재 값, 니가 만약 - 값을 리턴하면 첫번째 값이 두번째 값보다 작다고 판단
    // 큰값에서 작은 값 .sort((a,b)=>b-a)
    
    const result = students.map(student => student.score).sort((a,b)=>a-b).join();