배열의 내장함수 정리 - 1
at
정숫값을 받아 해당 인덱스에 있는 항목을 반환하며, 양수와 음수를 사용할 수 있으며, 음의 정수는 배열의 마지막 항목부터 거슬러 센다.
구문: at(index)
// 몇 가지 요소가 있는 배열
const cart = ["사과", "바나나", "배"];
// 주어진 배열의 마지막 요소를 반환하는 함수
function returnLast(arr) {
return arr.at(-1);
}
// 'cart' 배열에서 마지막 요소를 가져옴
const item1 = returnLast(cart);
console.log(item1); // '배'
// 'cart'배열에 요소를 추가
cart.push("오렌지");
const item2 = returnLast(cart);
console.log(item2); // '오렌지'
includes
매개변수를 받은 요소를 배열이 포함하고 있는지 판별하여 불리언(boolean) 값으로 반환한다.
구문: arr.includes(valueToFind[, fromIndex])
매개변수
valueToFind
탐색할 요소.> 참고: 문자나 문자열을 비교할 때, includes()는 대소문자를 구분한다.
fromIndex Optional
이 배열에서 searchElement 검색을 시작할 위치이다. 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색하며, 기본값은 0이다.
let colors = ["green", "blue", "purple"];
console.log(colors.includes("blue")); // true
console.log(colors.includes("yellow")); // false
let colors = ["green", "blue", "purple"];
console.log(colors.includes("blue", 2)); // false
console.log(colors.includes("blue", 1)); // true
Indexof
배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
구문: arr.indexOf(searchElement[, fromIndex])
매개변수
searchElement
배열에서 찾을 요소이다.
fromIndex Optional
검색을 시작할 색인이다. 인덱스가 배열의 길이보다 크거나 같은 경우 -1이 반환되므로 배열이 검색되지 않는다. 제공된 색인 값이 음수이면 배열 끝에서부터의 오프셋 값으로 사용된다.
참고 : 제공된 색인이 음수이면 배열은 여전히 앞에서 뒤로 검색된다. 계산 된 인덱스가 0보다 작 으면 전체 배열이 검색된다. 기본값 : 0 (전체 배열 검색).
let colors = ["green", "blue", "purple"];
2console.log(colors.indexOf("purple"));// 2
let colors = ["green", "blue", "purple"];
console.log(colors.indexOf("yellow")); // -1
let colors = ["green", "blue", "purple"];
console.log(colors.indexOf("blue", 2)); // -1
findIndex
주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환한다. 그리고 만족하는 요소가 없으면 -1을 반환한다.
indexOf는 특정 요소가 배열의 몇 번째 index 인지를 찾아주는 함수지만, indexOf 메서드는 배열 요소의 값이 객체형태거나, 배열의 형태일 때의 인덱스를 찾아주지 못하기 때문에 이런 경우 findIndex를 사용해야한다.
구문: findIndex(callbackFn), findIndex(callbackFn, thisArg)
매개변수
callbackFn
배열의 각 요소마다 실행할 함수이다. 일치하는 요소가 발견되었음을 나타내는 참인 값을 반환하고 그렇지 않으면 거짓인 값을 반환해야한다. 함수는 다음과 같은 인수와 함께 호출된다.
element
배열에서 처리중인 현재 요소이다.
index
배열에서 처리중인 현재 요소의 인덱스이다.
array
findIndex() 함수가 호출된 배열이다.
thisArg Optional
callbackFn을 실행할 때 this로 사용할 값이다.
let colors = [
{ id: 1, color: "green" },
{ id: 2, color: "blue" },
{ id: 3, color: "purple" }
];
let idx = colors.findIndex((elm) => elm.color === "purple");
console.log(idx); // 2
let colors = [
{ id: 1, color: "green" },
{ id: 2, color: "blue" },
{ id: 3, color: "purple" }
];
colors.findIndex((elm, idx, array) => console.log(`${idx} 번째 값 - id: ${elm.id}, color: ${elm.color}`));
colors.findIndex((elm, idx, array) => console.log(array));
find
주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환한다. 그리고 그런 요소가 없다면 undefined를 반환하게 된다.
구문: arr.find(callback[, thisArg])
매개변수
callback
배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받는다.
element
콜백함수에서 처리할 현재 요소.
indexOptional
콜백함수에서 처리할 현재 요소의 인덱스.
arrayOptional
find 함수를 호출한 배열.
thisArg
선택 항목. 콜백이 호출될 때 this로 사용할 객체.
let colors = [
{ id: 1, color: "green" },
{ id: 2, color: "blue" },
{ id: 3, color: "purple" }
];
let idx = colors.find((elm) => elm.color === "purple");
console.log(idx); // { id: 3, color: "purple" }
slice
어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환한다. 단, 원본 배열은 바뀌지 않는다.
구문: arr.slice([begin[, end]])
매개변수
begin Optional
0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미한다. 음수 인덱스는 배열의 끝에서부터의 길이를 나타낸다. slice(-2) 는 배열에서 마지막 두 개의 엘리먼트를 추출한다. begin이 undefined인 경우에는, 0번 인덱스부터 slice 한다. begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환한다.
end Optional
추출을 종료 할 0 기준 인덱스이다. slice 는 end 인덱스를 제외하고 추출한다. 예를 들어, slice(1,4)는 두번째 요소부터 네번째 요소까지 (1, 2 및 3을 인덱스로 하는 요소) 추출한다. 음수 인덱스는 배열의 끝에서부터의 길이를 나타낸다. 예를들어 slice(2,-1) 는 세번째부터 끝에서 두번째 요소까지 추출한다. end가 생략되면 slice()는 배열의 끝까지(arr.length) 추출한다.
만약 end 값이 배열의 길이보다 크다면, slice()는 배열의 끝까지(arr.length) 추출한다.
let colors = [
{ id: 1, color: "green" },
{ id: 2, color: "blue" },
{ id: 3, color: "purple" },
{ id: 4, color: "yellow" }
];
let sliceArray = colors.slice(1, 3);
console.log(sliceArray);