JavaScript

[JavaScript] #10 - 배열 (Array)

yoonddo 2023. 1. 14. 21:35

배열은 같은 자료들을 담는 자료구조 중 하나이다. 

객체는 어떤 개체에 대한 정보를 클래스로 틀을 만들고 그 클래스로 여러 개체들에 대한 정보를

담는것으로 배열과는 다르다.

예를들어 객체는 사람이라는 개체에 대한 정보를 담는 틀을 클래스로 만든다고 가정하면

이름, 키, 몸무게, 성별 ..등 다양한 정보를 사람이라는 공통된 개체에 대한 정보를 클래스로 만들어

마이크, 엘리스, 존 ..등 여러 객체를 찍어낼 수 있고 다양한 자료형을 담을 수 있다.

반면 배열은 단순하게 같은 자료형의 나열이라고 보면된다. 사람이라는 객체들을 나열할 수도, 정수를

나열할 수도 있다. 자바 스크립트는 다양한 자료형을 섞어 배열에 담을 수는 있지만 되도록 사용하지 않는다.

 

선언 (Declaration)

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

인덱스와 길이

const fruits = ['apple', 'banana'];
console.log(fruits);
console.log(fruits.length); // 2
console.log(fruits[0]); // apple
console.log(fruits[2]); // banana
console.log(fruits[1]); // undefined
console.log(fruits[fruits.length - 1]); // banana

//join
var array = [1, 2, 3];
array.join(); //결과 "1,2,3"
array.join(':'); //결과 "1:2:3"

//reverse
var array = [1, 2, 3, 4];
array.reverse(); //결과 [4, 3, 2, 1]
  • length : 문자열처럼 배열의 길이를 알려준다.
  • join : 배열의 항목들을 구분자를 기준으로 합친 새 문자열로 반환한다. 구분자를 입력하지 않으면 자동으로 쉼표이다.
  • reverse : 원래의 배열을 뒤집는다.

저장된 키와 값을 배열로 얻어오기

const doggy = {
	name: '멍멍이',
	sound: '멍멍!',
	age: 2,
}

//keys
console.log(Object.keys(doggy));
//결과 ['name', 'sound', 'age']
//-------------------------------------------------

//values
console.log(Object.values(doggy));
//결과 ['멍멍이', '멍멍!', 2]
//-------------------------------------------------

//entries
console.log(Object.entries(doggy));
//결과 [Array(2), Array(2), Array(2)]
//-------------------------------------------------
  • keys : 인수로 지정된 객체의 key 값을 배열로 묶어서 얻어온다.
  • values : 인수로 지정된 객체의 key에 할당된 value 값을 배열로 묶어서 얻어온다.
  • entries : 인수로 지정된 객체의 key와 value를 배열로 묶어 얻어온다.

배열의 반복문 (Looping over an array)

반복문을 이용해 배열의 모든 요소 출력하기

//세팅
const fruits = ['apple', 'banana', 'kiwi', 'melon'];

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

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

//forEach : 배열의 값마다 내가 전달한 함수 적용
fruits.forEach(function (fruit, index, array) {
  console.log(fruit, index, array);
});

//map
var array = [1,2,3];
array.map(function(x) {
  return x+1;
}); //결과 [2,3,4]

//화살표함수 -> 축약
fruits.forEach((fruit, index) => console.log(fruit, index, array));
//--------------------------------------------------------------------------

//reduce
var array = [1, 2, 3, 4, 5];
array.reduce(function(prev, cur) {
  return prev + cur;
}) //결과 15

//--------------------------------------------------------------------------

//filter
var array = [1,2,3,4,5];
array.filter(function(x) {
  return x % 2 === 0;
}); //결과 [2,4]
//--------------------------------------------------------------------------

//sort
var array = [5,2,3,4,1];
array.sort(function(x,y) {
  return x - y;
}); //결과 [1,2,3,4,5]
//--------------------------------------------------------------------------
  • forEach : 배열의 값마다 내가 전달한 함수를 적용해준다. forEach를 사용할 때는 콜백함수를
    사용하는데 콜백함수의 인자(값,인덱스,배열)로 정의하여 사용한다.
  • map : 배열의 항목들을 반복하면서 조작하는 함수로  map과 forEach의 차이점은 map은
    바뀐 새 배열을 반환하지만 forEach는 반환하지 않는다는 점이다. 따라서 map이 활용성이 더 높다.
  • reduce : 배열을 왼쪽부터 조건을 적용해 하나의 값으로 만든다. 배열.reduce(function(이전값,현재)
    {조건}); 의 형태로 사용한다. 오른쪽부터 줄여가고 싶다면 reduceRight 함수를 사용한다.
  • filter : 필터링 하는 함수로 특정 조건에 해당하는 배열만을 걸러내 새 배열로 만든다.
  • sort : 배열을 특정 조건에 따라 정렬한다.

배열 다루기

아래에서 소개하는 메서드는 전부 Array의 메서드이며 arr.메서드(); 형태로 사용한다.

그리고 모든 메서드들은 새로운 값을 리턴한다.

const fruits = ['apple', 'banana', 'kiwi', 'melon'];

//push
fruits.push('pear', 'berry');
console.log(fruits);
//결과 ['apple', 'banana', 'kiwi', 'melon', 'pear', 'berry']
//--------------------------------------------------------------------------

//pop
fruits.pop();
console.log(fruits);
//결과 ['apple', 'banana', 'kiwi', 'melon', 'pear']
//--------------------------------------------------------------------------

//unshift
fruits.unshift('berry', 'grape');
console.log(fruits);
//결과 ['berry', 'grape', 'apple', 'banana', 'kiwi', 'melon', 'pear']
//--------------------------------------------------------------------------

//shift
fruits.shift();
console.log(fruits);
//결과 ['grape', 'apple', 'banana', 'kiwi', 'melon', 'pear']
//--------------------------------------------------------------------------

//splice
fruits.splice(1, 1); // 인덱스 1부터 1개 삭제
console.log(fruits);
//결과 ['grape', 'banana', 'kiwi', 'melon', 'pear']

fruits.splice(3); // 인덱스 3부터 뒤로 전부 다 삭제
console.log(fruits);
//결과 ['grape', 'banana', 'kiwi']


fruits.splice(1, 1, 'grape', 'berry'); // 1인덱스부터 1개 삭제하고 그 자리에 'grape', 'berry' 추가
console.log(fruits);
//결과 ['grape', 'grape', 'berry', 'kiwi']
//--------------------------------------------------------------------------

//concat
const fruits2 = ['coconut', 'pear'];
const newFruits = fruits.concat(fruits2); // fruits에 fruits2을 연결한다.
console.log(newFruits);
//결과 ['grape', 'grape', 'berry', 'kiwi', 'coconut', 'pear']
//--------------------------------------------------------------------------

//from
Array.from([1,2,3], x=>x+1);
//결과 [2,3,4]

//빈배열
Array.from({ length: 1 });
//결과 [undefined]

Array.from({ length: 2 });
//결과 [undefined, undefined]

//빈배열 채우기
Array.from({ length: 8 }, (v, i) => i + 1); // v: value, i: index
// [1,2,3,4,5,6,7,8]
//--------------------------------------------------------------------------
  • push : 배열의 가장 마지막에서부터 값을 추가한다.
  • pop : 배열의 가장 마지막 값을 삭제한다.
  • unshift : 배열의 가장 앞에서부터 값을 추가한다.
  • shift : 배열의 가장 앞의 값을 삭제한다.
    (shift와 unshift는 정말 느리가 동작한다.)
  • splice : 배열에서 원하는 인덱스의 값을 삭제하거나 삭제하고 추가할 수 있다.
  • concat : 두 개의 배열을 연결한다.(합친다)
  • from : 특정 규칙을 가진 채로 배열을 만들어낼 수 있다. undefined라는 결과가 나와서
    오류라고 생각할 수 있지만 숫자를 바꾼 갯수만큼 늘어나는걸 확인할 수 있다.
    내용을 채워 넣을수도 있다.

검색하기

아래의 메서드들도 전부 Array의 메서드이며 arr.메서드(); 형태로 사용한다.

그리고 모든 메서드들은 새로운 값을 리턴한다.

const fruits = ['apple', 'banana', 'kiwi', 'apple', 'melon'];

//indexOf
console.log(fruts.indexOf('apple'))
//결과 0
console.log(fruts.indexOf('waterMelon')); // 없는 값을 입력하면 -1이 반환된다.
//결과 -1
//------------------------------------------------------------------

//lastIndexOf
console.log(fruts.lastIndexOf('apple'));
//결과 3
//------------------------------------------------------------------

//includes
console.log(fruts.include('apple'));
//결과 true
console.log(fruts.include('waterMelon'));
//결과 false
//--------------------------------------------------------------------------

//isArray
Array.isArray('array?'); //결과 false
Array.isArray(['array?']); //결과 true
//--------------------------------------------------------------------------

//every
var array = [1, 3, 5, 7, 9];
array.every(function(i) {
  return i % 2 === 1;
}); // true
array.every(function(i) {
  return i < 9;
}); // false
array.some(function(i) {
  return i === 9;
}); // true
//--------------------------------------------------------------------------
  • indexOf : 배열에서 처음으로 발견된 값의 인덱스를 리턴한다.
  • lastIndexOf : 배열에서 마지막으로 발견된 값의 인덱스를 리턴한다.
  • includes : 아이템이 배열에 포함되어 있으면 true, 포함되어있지 않으면 false를 리턴한다.
  • isArray : 배열인지 아닌지 확인해준다.
  • every : 배열의 모든 항목 또는 일부 항목이 true면 true를 반환한다. 즉 모든 항목이 조건을 만족하면
    true, some은 하나의 항목이라도 조건을 만족하면 true를 반환한다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

자료 출처 :https://www.zerocho.com/category/JavaScript/post/57387a9f715202c8679b3af0

, https://velog.io/@younoah/JS-%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EB%B0%B0%EC%97%B4-%EC%B4%9D%EC%A0%95%EB%A6%AC