✅ 배열이란?
여러 개의 값을 순차적으로 나열한 자료구조다. 자바스크립트에 배열이라는 타입은 존재하지 않는다. 배열은 객체 타입이다.
const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'Banana', 'Cherry']
console.log(numbers[1])
console.log(fruits)
zero based에 해당하는 0번째, 1번째 와 같은 것들을 index라고 부른다. 배열 데이터 내부의 데이터의 위치를 가리키는 숫자이다. 위와 같이 numbers[1] 대괄호를 열어서 index를 넣어서 조회하는 것을 indexing이라고 한다. 배열 안의 값을 element 즉 요소라고 하기도 하고 배열의 item이라고 한다.
🟢 배열 생성 방법
배열 리터럴
배열 리터럴은 가장 간단한 형태의 배열 생성 방법이다. 대괄호 []를 사용하여 배열을 생성하고, 원하는 요소를 쉼표로 구분하여 나열한다.
const fruits = ['apple', 'banana', 'cherry'];
Array 생성자 함수
Array 생성자는 여러 인자를 받을 수 있으며, 인자의 개수와 타입에 따라 배열의 동작이 달라질 수 있다.
const numbers = new Array(1, 2, 3); // [1, 2, 3]
const lengthOnly = new Array(5); // 배열의 길이가 5인 빈 배열 생성
Array.of()
Array.of 메서드는 인자로 전달된 값을 요소로 갖는 새로운 배열을 생성한다. 인자의 수나 타입에 상관없이 원하는 요소를 가진 배열을 생성할 수 있다.
const numbers = Array.of(1, 2, 3); // [1, 2, 3]
const singleItemArray = Array.of(5); // [5]
Array.from()
Array.from 메서드는 유사 배열 객체나 이터러블 객체(예: 문자열, Set, Map 등)를 배열로 변환하는 데 사용된다. 이 메서드는 새로운 배열을 생성한다.
const arrayLike = { 0: 'apple', 1: 'banana', length: 2 };
const arrayFromObject = Array.from(arrayLike); // ['apple', 'banana']
const str = 'hello';
const arrayFromString = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
요약
배열 리터럴은 간단한 초기화에 사용하고, Array 생성자 함수는 인자에 따라 동적으로 배열을 생성한다. Array.of는 인자를 배열 요소로 사용하여 일관된 배열을 만들고, Array.from은 다양한 데이터 소스를 배열로 변환하는 데 사용된다.
🟡 Array.isArray()
전달된 인수가 배열이면 true, 배열이 아니면 false를 반환한다.
// 모두 true 반환
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// Array.prototype은 스스로도 배열입니다
Array.isArray(Array.prototype);
// 모두 false 반환
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });
🟡 Array.prototype.indexOf()
지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// Expected output: 1
// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4
console.log(beasts.indexOf('giraffe'));
// Expected output: -1
Array.prototype.lastIndexOf()
주어진 값을 발견할 수 있는 마지막 인덱스를 반환, 존재하지 않으면 -1 반환.
🟡 Array.prototype.findIndex()
findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환한다. 만족하는 요소가 없으면 -1을 반환한다.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// Expected output: 3
🟡 Array.prototype.find()
find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
화살표 함수에서 매개변수가 하나(element)이면 매개변수를 감싸는 괄호를 생략해줄 수 있다. 함수 내부에서 간단한 실행문을 반환하는 경우 중괄호와 return키워드를 생략해줄 수 있다. find메소드 함수 부분에 새로운 함수를 넣어서 동작을 시키고 있으므로 인수로 사용되고 있는 이런 함수를 콜백이라고 한다.
- 배열에서 찾은 요소의 인덱스가 필요한 경우, findIndex()를 사용하세요.
- 값의 인덱스를 찾아야 하는 경우, indexOf()를 사용하세요. (findIndex()와 유사하지만, 테스트 함수를 사용하는 것 대신 각 요소가 값과 동일한지 확인합니다.)
- 배열에 값이 존재하는지 찾아야 하는 경우, includes()를 사용하세요. 이 역시 테스트 함수를 사용하는 것 대신 각 요소가 값과 동일한지 확인합니다.
- 제공된 테스트 함수를 만족하는 요소가 있는지 찾아야 하는 경우, some()을 사용하세요.
여기서 말하는 테스트 함수는 배열의 각 요소에 대해 조건을 검사하거나 특정 작업을 수행하는 함수를 의미함.
🟡 Array.prototype.includes()
배열의 항목에 특정 값이 포함되어 있는지를 판단하여 적절히 true 또는 false를 반환한다.
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// Expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// Expected output: true
console.log(pets.includes('at'));
// Expected output: false
includes(searchElement, fromIndex?)
searchElement: 찾을 값
fromIndex: 검색 시작 지점(Index)
반환값: boolean
🟡 Array.prototype.push() -원본이 수정됨
push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.
push 메서드는 성능 면에서 좋지 않다. 마지막 요소로 추가할 요소가 하나뿐이라면 push 메서드를 사용하지 않고 length 속성을 사용하는 방법이 있다. 이 방법이 push 메서드보다 빠르다.
const arr = [1, 2];
arr[arr.length] = 3;
console.log(arr); // [1, 2, 3]
ES6의 spread 문법을 이용하면 함수 호출 없이 표현식으로 마지막에 요소를 추가할 수 있으며 원본 배열을 직접 변경하는 부수 효과도 없다.
const arr = [1, 2];
const newArr = [...arr, 3]
console.log(newArr); // [1, 2, 3]
🟡 Array.prototype.unshift() -원본이 수정됨
unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환한다. unshift 메서드보다는 spread 문법을 사용하는 편이 좋다.
const arr = [1, 2];
const newArr = [3, ...arr]
console.log(newArr); // [3, 1, 2]
🟡 Array.prototype.reverse() -원본이 수정됨
reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 된다.
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
numbers.reverse()
fruits.reverse()
console.log(numbers)
console.log(fruits)
🟡 Array.prototype.toReversed()
reverse와 동일하게 요소의 순서가 뒤집히지만 원본 배열은 변하지 않는다.
🟡 Array.prototype.splice() -원본이 수정됨
splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다.
const numbers = [1, 2, 3, 4]
numbers.splice(2, 1)
console.log(numbers) // [1, 2, 4]
splice(2 ,1)의 첫번째 부분인 2는 배열 데이터의 인덱스 값. 에서 두번 째 부분인 1은 1개만 지운다는 의미이다.
splice(2 ,2)하면 [1, 2]가 출력된다.
const numbers = [1, 2, 3, 4]
numbers.splice(2, 0, 999)
console.log(numbers) // [1, 2, 999, 3, 4]
2인덱스 값에서 0개 삭제하고 999를 추가한다는 의미의 코드이다. splice(2, 1, 99)를 하면 3이 99로 교체된다.
const fruits = ['Apple', 'Banana', 'Cherry']
fruits.splice(2, 0, 'orange')
console.log(fruits)
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
start: 변경을 시작할 인덱스
deleteCount: 제거할 요소
item: 배열에 추가할 요소
🟡 Array.prototype.concat()
두 개의 배열 데이터를 병합하여 새로운 배열 데이터를 반환하여 준다. 원본의 데이터는 영향 받지 않는다.
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
console.log(numbers.concat(fruits))
console.log(numbers)
console.log(fruits)
🟡 Array.prototype.slice()
어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환한다.
let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
let citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
배열형 객체
slice() 메서드를 호출하여 배열형 객체와 콜렉션을 새로운 Array로 변환할 수 있다. (arguments, HTMLCollection, NodeList)
function convertToArray() {
// arguments 객체를 배열로 변환하기 위해 slice() 메서드를 바인딩합니다.
var args = Array.prototype.slice.call(arguments);
// 이제 args 변수는 arguments 객체의 복사본인 배열입니다.
console.log(args);
}
convertToArray(1, 2, 3); // [1, 2, 3]
🟡 Array.prototype.join()
배열의 모든 요소를 연결해 하나의 문자열로 만든다. MDN 링크
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// Expected output: "Fire,Air,Water"
console.log(elements.join(''));
// Expected output: "FireAirWater"
console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"
🟡 Array.prototype.fill()
배열의 인덱스 범위 내의 모든 요소를 전달받은 정적 값으로 변경한다.
const array1 = [1, 2, 3, 4];
// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]
// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]
console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]
fill(value)
fill(value, start)
fill(value, start, end)
🟡 Array.prototype.flat()
인수로 전달한 깊이만큼 재귀적으로 배열을 평탄화 한다.
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat()); // 기본값 1
// expected output: Array [0, 1, 2, 3, 4]
const arr2 = [0, 1, [2, [3, [4, 5]]]];
console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]
'개발자의 공부 > JS' 카테고리의 다른 글
[JS] 객체지향 프로그래핑 (0) | 2023.06.02 |
---|---|
[JS] class란? (0) | 2023.01.02 |
[JS문법] 일급 객체 (0) | 2022.12.26 |
[JS]생성자 함수에 의한 객체 생성 (0) | 2022.12.19 |
[JS]얕은 복사와 깊은 복사 (0) | 2022.09.29 |