일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- flex
- 프론트엔드
- for
- 문자열
- 타입
- 함수표현식
- 반복문
- properties
- 비교연산자
- javascript
- typeof
- Methods
- align-content
- 속성
- 논리연산자
- flex-wrap
- 함수
- if else
- flex-direction
- boolean
- 함수선언식
- ELSE
- 조건문
- 변수
- 화살표함수
- 기초
- frontend
- for in
- for of
- justify-content
- Today
- Total
하얀 코딩
[JavaScript - 6] Array 객체 메서드 본문
String 객체 함수와 똑같이 쓰이는 메서드!
이번 글에서는 Array에서 쓸 수 있는 전용 객체 함수만 다루어 봅니다.
밑에는 사용법은 String 객체 함수와 똑같기에 설명은 따로 하지 않습니다.
- Array.prototype.includes()
- Array.prototype.indexOf()
- Array.prototype.lastIndexOf()
- Array.prototype.slice() <-- 중요하기에 이번 글에서 다룹니다.
- Array.prototype.concat() <-- 중요하기에 이번 글에서 다룹니다.
Array.prototype.splice()
배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
1. start
배열의 변경을 시작할 인덱스입니다. 배열의 길이보다 큰 값이라면 실제 시작 인덱스는 배열의 길이로 설정됩니다.
음수인 경우 배열의 끝에서부터 요소를 새어나갑니다(원점 -1, 즉 -n이면 요소 끝의 n번째 요소를 가리키며 array.length - n번째 인덱스와 같음). 값의 절대값이 배열의 길이보다 큰 경우 0으로 설정됩니다.
2. deleteCount
배열에서 제거할 요소의 수입니다. deleteCount를 생략하거나 값이 array.length - start보다 크면 start부터의 모든 요소를 제거합니다. deleteCount가 0 이하라면 어떤 요소도 제거하지 않습니다. 이 때는 최소한 하나의 새로운 요소를 지정해야 합니다.
3. item1, item2 ...
배열에 추가할 요소입니다. 아무 요소도 지정하지 않으면 splice()는 요소를 제거하기만 합니다.
4. return
제거한 요소를 담은 배열을 반환합니다. 아무 값도 제거하지 않았으면 빈 배열을 반환합니다.
5. 파괴 함수(mutable)이다. (원본을 변경)
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
Array.prototype.slice()
어떤 배열의 begin부터end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다.
arr.slice([begin[, end]])
1. begin
0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미합니다. 음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. slice(-2)는 배열에서 마지막 두 개의 엘리먼트를 추출합니다. begin이 undefined인 경우에는, 0번 인덱스부터 slice 합니다. begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환합니다.
2. end
추출을 종료할 0 기준 인덱스입니다. slice는 end 인덱스를 제외하고 추출합니다. 예를 들어, slice(1,4)는 두 번째 요소부터 네번째 요소까지 (1, 2 및 3을 인덱스로 하는 요소) 추출합니다. 음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 예를들어 slice(2,-1) 는 세번째부터 끝에서 두번째 요소까지 추출합니다. end가 생략되면 slice()는 배열의 끝까지(arr.length) 추출합니다.
3. return
추출한 요소를 포함한 새로운 배열을 반환.
4. 비파괴 함수(immutable)이다. (원본을 변경하지 않음)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
Array.prototype.unshift()
새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.
arr.unshift([...elementN])
1. elementN
배열 맨 앞에 추가할 요소.
2. return
메서드를 호출한 배열의 length 값을 반환.
3. 파괴 함수(mutable)이다. (원본을 변경)
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Array.prototype.shift()
메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다.
arr.shift()
1. return
배열에서 제거한 요소를 반환합니다. 빈 배열의 경우 undefined를 반환합니다.
2. 파괴 함수(mutable)이다. (원본을 변경)
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Array.prototype.push()
배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환
arr.push(element1[, ...[, elementN]])
1. elementN
배열의 끝에 추가할 요소.
2. return
메서드를 호출한 배열의 length 값을 반환.
3. 파괴 함수(mutable)이다.(원본을 변경)
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Array.prototype.pop()
배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.
arr.pop()
1. return
배열에서 제거한 요소를 반환. 빈 배열의 경우 undefined 를 반환합니다.
2. 파괴 함수(mutable)이다. (원본을 변경)
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
Array.prototype.concat()
인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.
array.concat([value1[, value2[, ...[, valueN]]]])
1. 매개변수
배열 또는 값
2. 반환값
새로운 Array 객체.
3. 만약 value1 ~ valueN 인자를 생략하면 기존배열의 얕은 복사본을 반환.
4. 배열이나 값을 이어붙여도 원본은 변하지 않으며, 새로운 배열이나 원본 배열을 조작해도 서로 영향을 받지 않습니다.
5. 비파괴 함수(immutable)이다. (원본을 변경하지 않음)
6. 실제 객체가 아닌 객체 참조: concat은 새 배열에 참조를 복사합니다. 원본 배열과 새 배열에서 같은 객체를 가리키게 됩니다. 즉, 참조하는 객체를 수정하면 그 내용이 새 배열과 원본 배열 둘 다에서 나타납니다.
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// output: ["a", "b", "c", "d", "e", "f"]
const alpha = ['a', 'b', 'c'];
alpha.concat(1, [2, 3]);
// output: ['a', 'b', 'c', 1, 2, 3]
Array.prototype.join()
배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
arr.join([separator])
1. separator
배열의 각 요소를 구분할 문자열을 지정합니다. 이 구분자는 필요한 경우 문자열로 변환됩니다. 생략하면 배열의 요소들이 쉼표로 구분됩니다. separator가 빈 문자열이면 모든 요소들이 사이에 아무 문자도 없이 연결됩니다
2. return
배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. arr.length 가 0이라면, 빈 문자열을 반환합니다.
(요소가 undefined 또는 null이면 빈 문자열로 변환합니다.)
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.sort()
sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.
기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.
정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다.
arr.sort(compareFunction)
1. compareFunction
정렬 순서를 정의하는 함수를 넣어야 합니다.
생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니코드 코드 포인트 값에 따라 정렬됩니다.
2. return
정렬한 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.
3. 설명
compareFunction의 정렬 조건에 의한 리턴 값 기준으로 원하는 정렬을 설정 할 수 있습니다.compareFunction 함수의 형식은 다음과 같은 개념으로 동작합니다.
function compare(a, b) {
if (어떤기준에 의해 a가 b보다 작다) {
return -1;
}
if (어떤기준에 의해 a가 b보다 크다) {
return 1;
}
// 어떤기준에 의해 a랑 b랑 같다.
return 0;
}
리턴 값으로 인해 순서를 정렬하는 모습을 알 수 있다!
그렇다면 응용해서 써볼까?
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// value 기준으로 정렬
items.sort(function (a, b) {
if (a.value > b.value) {
return 1;
}
if (a.value < b.value) {
return -1;
}
// a must be equal to b
return 0;
});
// name 기준으로 정렬
items.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// 이름이 같을 경우
return 0;
});
Array.prototype.reverse()
reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.
a.reverse()
1. return
순서가 반전된 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.
Array.isArray()
메서드는 인자가 Array인지 판별합니다.
Array.isArray(obj)
1. obj
검사할 객체
2. return
객체가 Array라면 true, 아니라면 false.
Array.isArray([1, 2, 3]); // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar'); // false
Array.isArray(undefined); // false
Array.from()
유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듭니다.
Array.from(arrayLike[, mapFn[, thisArg]])
1. arrayLike
배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.
2. mapFn (Optional)
배열의 모든 요소에 대해 호출할 맵핑 함수.
3. thisArg (Optional)
mapFn 실행 시에 this로 사용할 값.
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
유용하게 쓰일 수 있는 메서드!
MDN을 참고해 사용법을 익혀보자!
- Array.prototype.some()
- Array.prototype.every()
- Array.prototype.at()
- Array.prototype.entries()
- Array.prototype.find()
- Array.prototype.findLast()
- Array.prototype.findIndex()
- Array.prototype.findLastIndex()
다음에 다루어 볼 것! (고차함수)
여기서 다루기엔 난이도가 높은 메서드들이다. MDN을 통해 자세히 알아보거나 제 글에서 확인 하실 수 있습니다.
- Array.prototype.map()
- Array.prototype.filter()
- Array.prototype.reduce()
- Array.prototype.forEach()
'JavaScript' 카테고리의 다른 글
[JavaScript - 8] 원시 / 참조 자료형 (0) | 2022.11.08 |
---|---|
[JavaScript - 7] 객체 (0) | 2022.11.08 |
[JavaScript - 5] 반복문 for / for of / for in (0) | 2022.10.25 |
[JavaScript - 4] 문자열 메서드 (0) | 2022.10.24 |
[JavaScript - 3] 연산자 / Boolean / 조건문 (if / else if / else) (0) | 2022.10.24 |