본문 바로가기
JavaScript/드림코딩 엘리 - 자바스크립트 기초 강의 (ES5+)

드림코딩 엘리 - 자바스크립트 기초 강의(ES5+) (8편)

by 정ㅇr 2021. 11. 15.
728x90

배열에 관한 내용

간단한 개념 정리

- 비슷한 종류의 데이터를 묶어 놓는 것 = 자료구조

- Object : 서로 연관된 것들끼리 묶어 놓는 것

- 비슷한 타입의 Object들을 묶어 놓는 것을 자료구조라고 이해하면 된다.


배열을 정의하는 방법과 인덱스를 활용하는 법

// 1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];

// 2. Index position
const fruits = ['apple', 'banana'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]); // 배열의 인덱스에 해당하는 값을 출력한다.
console.log(fruits[fruits.length - 1]); // 배열의 마지막 값을 찾을 때 배열의 길이를 활용해서 쓸 수 있음

반복문

// 3. Looping over an array
// print all fruits
// a. for
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

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

// c. forEach (콜백 함수를 받아온다)
fruits.forEach((fruit) => console.log(fruit));

// 내 답안
// for(const a of fruits) {
//     console.log(a);
// }

자바스크립트 내에 들어있는 메소드 API를 클릭하면, 그 메소드에 대한 정보를 볼 수 있다.

forEach를 잠시 살펴보면, 이 메소드는 인자를 2개를 받아오는걸 알 수 있다.

하나는 콜백함수, 다른 하나는 ?로 되어 있는데 물음표로 되어 있는 인자는 필수요소는 아니다.

콜백함수 인자 내용은 배열의 값, 인덱스, 그리고 배열 전체를 받아온다는 것을 알 수 있다.


배열 추가, 삭제, 복사 (Addition, Deletion, Copy)

// 4. Addtion, deletion, copy
// 배열의 맨 뒤에서 값을 더하거나 뺄 때
// push: add an item to the end
fruits.push('grape', 'peach');
console.log(fruits);


// pop: remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits)

// 배열의 맨 앞에서 값을 더하거나 뺄 때
// unshift: add an item to the beginning
fruits.unshift('strawberry', 'lemon');
console.log(fruits);

// shift: remove an item from the beginning
fruits.shift();
fruits.shift();
console.log(fruits);

// note!! shift, unshift are  slower than pop, push
// 그 이유는 배열의 맨 뒤에서 데이터를 삭제하고 추가하는 것은 인덱스를 이용해서
// 비교적 쉽게 처리할 수 있으나,
// 맨 앞에 데이터를 추가하고 삭제하는 것은 기존에 있던 데이터의 자리를 옮기고
// 그 다음에 추가, 삭제를 처리하기 때문에 더 느리고 오래 걸린다.
// 참고로 이와 관련된 것은 정렬이나 bigO 개념이다.

// splice: remove an item by index position
fruits.push('strawberry', 'peach', ' lemon');
console.log(fruits);
// fruits.splice(1); // 인덱스를 지정하고 몇개를 지울건지 입력하지 않으면, 그 지정한 인덱스를 포함한 모든 데이터를 삭제한다.
fruits.splice(1, 1); // 지정한 인덱스를 포함해서 1개를 지움 = 지정한 인덱스 값만 삭제됨
console.log(fruits);
fruits.splice(1, 1, 'watermelon', 'orange'); // 값을 삭제한 그 자리에 원하는 값을 추가할 수 있다.
console.log(fruits);
// 배열의 원하는 자리에 값을 삭제하지 않고, 새로운 데이터를 추가할 수도 있다.
fruits.splice(1, 0, 'hi', 'good');
console.log(fruits);

// concat: combine two arrays
const fruits2 = ['pear', 'coconut'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

검색 (Searching)

// 5. Searching
// indexOf: find the index
console.log(fruits);
console.log(fruits.indexOf('apple'));
console.log(fruits.indexOf('watermelon'));
// 배열에 없는 값의 인덱스를 출력하면 -1이 나옴
console.log(fruits.indexOf('hello'));

// includes: 배열에 해당 값이 있는지 없는지 확인
// true or false 리턴함
console.log(fruits.includes('apple'));

// lastIndexOf
// 배열에 동일한 값이 2개 들어 있을 때
// indexOf는 앞에 위치한 값의 인덱스를 출력
// lastIndexOf는 뒤에 위치한 값의 인덱스를 출력한다.
fruits.push('apple');
console.log(fruits);
console.log(fruits.indexOf('apple'));
console.log(fruits.lastIndexOf('apple'));

 

반응형

댓글