Array_8.js

Hey! ·2020년 10월 28일
0

javaScript

목록 보기
3/3

비슷한 물건들을 한 곳에 담아놓는 것과 같이, 프로그래밍 언어에서도 비슷한 종류의 데이터들을
한 바구니에 담아 보관.
=> 자료구조
어떤방식, 어떤형식으로 데이터를 담느냐에 따라 굉장한 차이가 발생
===> object 와 자료구조 차이?
object : 토끼 = { 귀 2개, function 먹는다, function 뛴다.(행동이 있으므로 method)}, 당근 [이미지1]
==> 서로 연관된, 특징들을 묶어놓는다. ex) 토끼, 사람, 자동차, 은행
==> 토끼, 당근들을 담아놓는 것 : 자료구조 (동일한 type 의 데이터만 담을수 있으나,
dynimically typed language 이므로 다양한 종류의 date type을 넣을 수 있찌만, 지양한다.)
앞으로 계속 자료구조, 알고리즘 공부해라.
물건들을 한데 담아놓은 자료구조 (array, map,set,list) 중에서도 새로운 data를 자료구제에
삽입, 검색, 정렬, 삭제 할때 어떤 알고리즘을 사용해야 효율적으로 코딩할수 있는지를 공부해야한다.
이런것들이 프로그래머스, 인터뷰에서 나오는 문제들이다.
많은 자료구조 중에서 어떤 자료구조를 선택할지, 그 선택할떄 검색, 삽입, 정렬, 삭제 할떄 O(빅 O)를
생각해야 한다.

이미지2, 이렇게 배열을 이용해서 자료를 보관. 이미지3은 가능, but 지양
배열은 인덱스로 접근 가능!! ==> 인덱스 덕에 삽입, 삭제가 매우 쉬움!!

Array

1. Declaration

const arr1 = new Array();  
const arr2 = [ 1,2 ]; // 더 많이 쓴다!!

2. Index position

const fruits = ['사과', '바나나'];
console.log(fruits);
console.log(fruits.length);
// 오브젝트에서는 키에 상응하는 value들을 받아올수 있었따.
// ex. const ob = { banana : ellie }
// console.log( ob['banana'] }  ; computed properties
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[fruits.length - 1 ]); // 배열의 마지막 인덱스가 출력됨.

3. Looping over an array

1) for 방법

for ( let i = 0; i <fruits.length; i++){
    console.log(fruits[i]);
}

2) for - of 방법

(*주의 : 위의 for ( let i = 0; i <fruits.length; i++)처럼..
앞에 let으로 변수선언하지 않으면, fruit declare라고 오류뜬다. )

for ( let fruit of fruits){
    console.log(fruit);

3) forEach ; API , 콜백함수를 받아오는 함수.

fruits.forEach();

ctrl 누르고 forEach()클릭하면, 정의되어있는 API로 이동한다.

API를 능동적으로 찾아보며 쓰는 연습을 해야한다!!

찾아보면...

  • Performs the specified action for each element in an array.
    (해석 : array들어있는 값마다 callback함수를 수행한다. )
    @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;

    forEach의 인자값은 2개이다.
    -> 1. callbackfn: (value: T, index: number, array: T[]) => void ;
    -> 2. thisArg?: any // '?' 는 필수 인자값이 아니라는 뜻

fruits.forEach( function( fruits, index, array ){
    console.log('he');  // 이미지5_ 2 he ; he가 2번 출력됨. 이유; furits안에 2개의 element 가 있기때문.
    console.log(fruits); 
    console.log(index);
    console.log(fruits,index);
    console.log(array);
    console.log(fruits, index, array);
})          // 이미지 6 

console.clear();

cf. anonymous function ; Arrow funcrion 사용 가능! (주의 ; 1) ()로 function의미 / 2) return 되는 한줄로직에 ';' 찍지 않는다.

cf. anonymous function ;  Arrow funcrion 사용 가능!  (주의 ; 1) ()로 function의미  / 2) return 되는 한줄로직에 ';' 찍지 않는다. 

4) Addition, deletion, copy

__01. push : add an item to the end

fruits.push('딸기','복숭아');
console.log(fruits);

__02. pop : remove an item from the end

fruits.pop();
fruits.pop();
console.log(fruits);

__03. unshift : add on item to the beginning

fruits.unshift('망고', '천도복숭아');
console.log(fruits);

__04. shift : remove on item to the beginning

fruits.shift();
fruits.shift();
console.log(fruits);

* Note!!!!!

 shift, unshift are much slower than pop, push

이유; 뒤에서부터 넣고, 빼는것은.. 마지막의 빈 공간(인덱스를 이용)에 데이터를 삽입,삭제하므로
기존의 데이터들은 움직이지 않는다.
반대로..
unshift ; 맨 앞에 데이터를 넣기 위해서, ... 3번쨰 item 을 4번째로 / 2번째 item을 3번쨰로 옮겨서,
맨 처음 자리에 빈공간을 만들어 줘야 한다. (이미지8)
shift ; 첫번째 있는 item 을 지우고, 2번째 item을 1번째로 앞으로 댕겨오고 / 3번째 item 을 2번째로 댕겨온다..
==> 맨 뒤에서 데이터에 접근하는것은 굉장히 빠르다!
(pop / push 쓰는것을 추천!)
+) 중간에 데이터를 삽입, 삭제 하는 것도 '인덱스'를 활용 하기 때문에 빠르다!!!
// But > 전체의 데이터를 움직여야 하는 것은 굉장히 느리다 + 배열의 길이가 길수록 전체데이터를 움직일때 더 느려진다.

5)remove an item by index position ;

splice : remove an item by index position

fruits.push('딸기', '복숭아', '레몬');
console.log( fruits);

//fruits.splice(1); // 시작 index번호~ 전부 지운다!
//console.log(fruits);
//fruits.splice(1,1); // 시작 index, 지우는 갯수

fruits.splice(1, 1, '사과', '수박');   // 시작 index, 지우는 갯수 ( == 1번 index삭제), 삭제한 자리에 넣을  item
console.log(fruits);

5. Searching

find the index

console.clear();
console.log(fruits);
console.log(fruits.indexOf('사과'));
console.log(fruits.indexOf('황금향'));  // 없으면 -1이 반환됨.

includes

console.log(fruits.includes('사과'));  // true
console.log(fruits.includes('구아바')); //false

lastIndexOf

console.clear();
fruits.push('사과');
console.log(fruits);
console.log(fruits.indexOf('사과')); // indexOf(); 가장 첫번째에 만난 값을 만나면, 그 값을 return한다. 
console.log(fruits.lastIndexOf('사과')); // lastindexOf(); 가장 마지막에 만난 값을 return
profile
Struggling to make it by myself!

0개의 댓글