WEB/JAVASCRIPT

[자바스크립트]Array 배열 개념 공부

aimee418 2023. 3. 26. 21:03

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

- Frederick Philips Brooks
Mythical Man-Month 저자
728x90
반응형

Array배열 개념 이해하기

 

배열은 자바스크립트에서 데이터를 순서대로 담는 자료구조 입니다.

배열 안에는 여러 개의 값들이 순서대로 나열 되어 있으며, 각 값들은 인덱스(Index)를 이용해 접근 할 수 있습니다.

인덱스는 첫 번째 요소가 0부터 시작하여 1씩 증가하는 정수 입니다.

 

배열은 '[ ]' 대괄호로 생성하며, 생성 시 배열의 초기값을 지정할 수 있습니다.

const arr1 = [1, 2, 3]; // 초기값을 지정한 배열
const arr2 = []; // 빈 배열

배열에는 다양한 메서드(method)가 존재합니다. 이 메서드들을 사용하여 배열에 요소를 추가, 삭제, 검색하는 등 다양한 작업을 할 수 있습니다. 예를 들어, 다음은 배열의 'push()'메서드를 사용하여 배열의 끝에 요소를 추가하는 방법입니다.

const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]

위 예제에서는 'push()'메서드를 사용하여 배열'arr'의 끝에 요소 '4'를 추가하였습니다. 이렇게 추가된 요소는 인덱스로 접근할 수 있으며, 다음과 같이 '[ ]'대괄호를 사용하여 접근할 수 있습니다.

const arr = [1, 2, 3, 4];
console.log(arr[0]); // 1
console.log(arr[1]); // 2
console.log(arr[2]); // 3
console.log(arr[3]); // 4

배열은 다른 자료구조와 함께 사용되어 자료를 효과적으로 처리할 수 있습니다. 예를 들어, 배열과 반복문을 함께 사용하여 배열의 모든 요소를 출력하는 코드는 다음과 같습니다. 

const arr = [1, 2, 3, 4];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Array.

01. Declaration

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

 

02. Index position

const fruits = ['🍎', '🍌'];
        console.log(fruits);
        console.log(fruits.length);
        console.log(fruits[0]);
        console.log(fruits[1]);
        console.log(fruits[2]);
        console.log(fruits[fruits.length -1]);//배열의 마지막 요소를 도출할 때 쓰는 식. 인덱스가 0부터 시작하기 때문에

 

03. 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문 : 배열 안에 들어있는 value들 마다 내가 전달한 함수를 출력한다.

fruits.forEach((fruits) => console.log(fruits));

✈ forEach(callbackfn: (value: T, index: number, array ; T[ ]) =>void, thisArg?: any : void;)

//배열의 각 요소가 각각 콜백함수를 수행한다.

 

 

 

 


배열에 쓰이는 필수 APIs

01. push : add an items to the end

fruits.push('🍓','🍑');
console.log(fruits);

//'🍎', '🍌', '🍓', '🍑'

02. pop: remove an item to the begining

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

//'🍎', '🍌'

//03. unshift: add an item from the end

        fruits.unshift('🍊','🥝');
        console.log(fruits);

//'🍊', '🥝', '🍎', '🍌'

04. shift : remove an item from the beging

        fruits.shift()
        console.log(fruits)

//'🥝', '🍎', '🍌'

o5. splice : remove an item by index position

        fruits.splice(0, 1); //배열 넘버, 삭제할 배열 개수 
        console.log(fruits)
        fruits.splice(0, 3, '🍖','🍟');//지우고 데이터 넣기
        console.log(fruits)

//'🍎', '🍌', '🍋', '🥕', '🍔'

//'🍖', '🍟', '🥕', '🍔'

06. combine two arrays

        const fruits2 = ['🍳', '🧇'];
        const newFruits = fruits.concat(fruits2); //배열 합치기
        console.log(newFruits);

//'🍖', '🍟', '🥕', '🍔', '🍳', '🧇'

07. searching

indexOf

        console.log(fruits.indexOf('🍖'));//0 : 배열이 위치한 배열넘버 도출
        console.log(fruits.indexOf('🍟'));//1
        console.log(fruits.indexOf('🥖'))//-1 : 배열에 속해있지 않으면 -1

 

include

        console.log(fruits.includes('🥖'))//false : 불리언 도출
        console.log(fruits.includes('🍟'))//true

lastIndexOf

        console.clear();
        fruits.push('🍖');
        console.log(fruits)
        console.log(fruits.indexOf('🍖')) //앞에서부터 몇번째에 첫 닭다리가 있는지
        console.log(fruits.lastIndexOf('🍖')) //뒤에서부터 몇번째에 첫 닭다리가 있는지