8.array

2 minute read

1. 배열(array)란

  • 비슷한 물건끼리 한곳에 모아두는것처럼 , 비슷한 종류의 데이터들을 묶어서 한곳에 모아두는것을 “자료구조” 라고 한다. 그리고 그 자료구조중 하나가 배열이다

2. 배열과 Object(객체) 차이는?

Object는 Property(키 : value)로만 존재한다. 즉 토끼로 예를들면

const rabbit = { ears: "two", eating: function () {} };
const carrot = { color: "red", nutrients: "VitaminC" };

그리고 이 비슷한것들을 묶어 놓는것을 자료구조라고 하며, 동일한 타입의 데이터들만 묶는다. 하지만 자바스크립트는 값에 의해서 데이터타입이 정해지므로 동일하지 않은 타입의 데이터가 묶이는 경우가 있을수도 있는데, 좋은 코딩이라고 할수 없다.

const array = [rabbit, carrot]; // bad example

배열은 이러한 자료구조중 하나며, 칸막이로 막아져 있는 형태를 지닌다. (index는 0부터 시작함)

const rabbitArray = [rabbit, rabbit1, rabbit2];

3. 배열 선언

const arr1 = new Array();
const arr2 = []; //더 흔하게 사용됨

4. 배열의 접근

const fruits = ["apple", "banana"];

console.log(fruits[0]); //fruits[index]
console.log(fruits[2]); //undefined
// 객체에 접근할때도 []를 사용했는데 , 객체는 key 로 접근한다. ['key']

5. 배열의 탐색

    1. for 을 사용한다.
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
    1. for of
for (let fruit of fruits) {
  console.log(fruit);
}

(for-in 도 있는데 for in은 객체의 키를 순환할때 사용됨)

    1. forEach
fruits.forEach((fruit) => {
  console.log(fruit);
});

5. 배열의 더하기, 빼기 , 복사

  • 데이터 더하기(push) , 마지막에 데이터가 들어감

    • push
    const fruits = ["apple", "banana"];
    fruits.push("berry", "orange");
    
    console.log(fruits); //"apple", "banana" , "berry","orange"];
    
    • 데이터 배기(pop) , 마지막 데이터가 삭제됨
    const fruits = ["apple", "banana"];
    fruits.pop();
    console.log(fruits); //["apple"]
    
    • 데이터 더하기(2)(unshift) : 첫번째에 데이터가 들어감
    const fruits = ["apple", "banana"];
    fruits.unshift("berry", "orange");
    console.log(fruits); //"berry","orange","apple", "banana" ];
    
    • 데이터 빼기(2)(shift) : 첫번째부터 데이터를 뺌
    const fruits = ["apple", "banana"];
    fruits.shift();
    console.log(fruits); //["banana"]
    

6. shift 와 unshift

  • 하지만 shift 와 unshift 는 pop()과 push()보다 훨씬 느림

  • 그 이유는 마지막 번째는 데이터가 자유롭게 들어갓다, 뺄수 있는데 첫번째에 데이터가 들어가거나 위해서는 그 뒤에 데이터가 한칸씩 뒤로 이동해야하기 때문이며 , 빼기위해서는 첫번째 데이터가 지워지면 나머지 뒤에있는 데이터들이 한칸씩 앞으로 땡겨와야하기 때문이다.

7. 지정된 데이터를 지우기

  • splice(index,number) : index부터 몇개(number)까지 지울것인지, number을 지정하지 않으면 지정한 index부터 다 지움

  • 7.1 지정된 데이터 지우기

const fruits = ["apple", "banana", "lemon", "peach"];

fruits.splice(1, 2);
//index 1부터 2개를 지울것이다.
//["apple","peach"]
  • 7.2 지정된 데이터를 지우고 그 자리에 데이터를 추가시키기
const fruits = ["apple", "banana", "lemon", "peach"];
friuts.splice(1, 1, "orange", "kiwi");

console.log(fruits); //["apple", "orange", "kiwi", "lemon", "peach"];
  • 7.3 지정한 위치에 데이터 넣기
const fruits = ["apple", "banana", "lemon", "peach"];
friuts.splice(1, 0, "orange", "kiwi");

console.log(fruits); //["apple", "orange", "kiwi","banana" "lemon", "peach"];
  • 7.4 두개의 데이터를 합치기
const fruits = ["apple", "banana", "lemon", "peach"];
const fruits2 = ["melon"];

const newfruits = fruits.concat(fruits2);

console.log(newfruits);

//["apple", "banana", "lemon", "peach", "melon"]

8. 데이터 찾기

  • 8.1 indexOf : 데이터의 index 찾기
const fruits = ["apple", "banana", "lemon", "peach"];

console.log(fruits.indexOf("apple")); //0
console.log(fruits.indexOf("pizza")); //-1
  • 8.2 includes : 데이터가 있는지 없는지 확인하기
const fruits = ["apple", "banana", "lemon", "peach"];

console.log(fruits.includes("apple")); //true
console.log(fruits.includes("pizza")); //false
  • 8.3 lastIndexOf : 배열의 마지막에서 index가 어딨는지 찾기
const fruits = ["apple", "banana", "lemon", "peach"];

fruits.push("apple"); //true

console.log(fruits.indexOf("apple")); // 0
console.log(fruits.lastIndexOf("apple")); //4

Leave a comment