JavaScript에서 배열은 기본적으로 값 목록을 보유하는 데이터 구조입니다.
이 값은 문자열, 정수 또는 객체 일 수 있습니다. 배열에는 고정 유형이나 길이가 제한되어 있지 않습니다.
https://dev.to/rebeccauranga/10-array-methods-you-should-know-nn5
배열은 대괄호를 사용하여 참조됩니다. [] 요소의 색인은 단순히 배열에 있는 요소의 "위치"를 의미합니다.
1이 아닌 0부터 시작하여 요소의 인덱스를 계산합니다.
예를 들어, newArray = [1, 2, 3, 4]; 이 경우 1은 0 위입니다.
색인을 대괄호 []와 함께 사용하여 항목을 검색 할 수 있습니다.
예를 들면 다음과 같습니다. newArray [0] 1을 반환합니다.
newArray [2]는 3을 반환합니다.
다른 예로는 cats = [ "Sebastian", "Emmy", "Mr.Whiskers"]; 고양이 [1]는 "Emmy"를 반환합니다.
이러한 기본 개념을 알고 있으면 배열 방법을 배울 수 있습니다.
로직을 간소화하고 효율적으로 만들 수있는 다양한 방법이 있다는 것을 빨리 알게 될 것입니다.
다음은 일반적으로 사용되는 10 가지 방법입니다. ?
방법 ?
1) .push() | 배열의 끝에 요소를 추가
let names = ["Nick", "Chris", "Ben"];
names.push("Rebecca");
console.log(names);
// names = ["Nick", "Chris", "Ben", "Rebecca];
2) .pop | 배열의 마지막 요소를 제거합니다
let cities = ["New York", "Los Angeles", "Atlanta"];
cities.pop();
console.log(cities);
// cities = ["New York", "Los Angeles"];
3) .shift | 배열의 첫 번째 요소를 제거합니다
let ages = [30, 26, 24, 20];
ages.shift();
console.log(ages);
// ages = [26, 24, 20]
4) .unshift | 배열의 시작 부분에 요소를 추가합니다
let ages = [30, 26, 24, 20];
ages.unshift(60);
console.log(ages);
// ages = [60, 30, 26, 24, 20];
5) .splice | 주어진 색인에서 요소를 추가, 제거 또는 대체합니다. 첫 번째 매개 변수는 색인이고 두 번째 매개 변수는 제거 할 요소 수이며 세 번째 매개 변수는 바꾸거나 추가 할 값입니다.
// to remove elements
let animals = ["cat", "dog", "shark", "horse", "alligator"];
animals.splice(1, 2);
// remove 2 elements at index 1, including index 1
// so what's being "spliced" is "dog" and "shark"
console.log(animals);
// animals = ["cat", "horse", "alligator"];
// to add elements
let animals = ["cat", "dog", "shark", "horse", "alligator"];
animals.splice(2, 0, "zebra");
// at index 2, splice (or remove) 0 elements, add "zebra"
animals = ["cat", "dog", "zebra", "shark", "horse", "alligator"];
// to replace elements
let animals = ["cat", "dog", "shark", "horse", "alligator"];
animals.splice(2, 1, "zebra");
// an index 2, replace 1 element ("shark") with "zebra"
// at index 2, splice (or remove) 0 elements, add "zebra"
animals = ["cat", "dog", "zebra", "horse", "alligator"];
6) .slice | 배열의 얕은 복사본을 반환합니다. 슬라이스 하려는 위치의 "시작"및 "종료"를 나타내는 하나 또는 두 개의 매개 변수를 사용할 수 있습니다. "시작"매개 변수는 포함되지만 "end"매개 변수는 포함되지 않아야 합니다.
let colors = ["Blue", "Red", "Orange", "Purple", "Pink"];
let lessColors = colors.slice(1, 3);
console.log(lessColors);
// colors = ["Red", "Orange"];
? 하나의 매개 변수만 포함하면 "시작"값 뒤에 모든 요소가 유지됩니다.
let colors = ["Blue", "Red", "Orange", "Purple", "Pink"];
let lessColors = colors.slice(2);
// colors[2] = "Orange" which now becomes the 1st element
console.log(lessColors);
// lessColors = ["Orange", "Purple", "Pink];
❗️ .splice와 .slice는 기억하기 어려울 수 있습니다. splice는 요소를 제거, 교체 또는 추가하고 기존 배열을 수정할 수 있는 매우 동적인 방법이라고 생각합니다.
반면 slice는 주로 값을 제거하고 새 배열을 만듭니다.
7) .forEach | 배열의 각 요소에 대한 기능을 수행합니다.
let miles = [1, 3, 5, 10];
let moreMiles = [];
miles.forEach(element => moreMiles.push(element + 10))
console.log(moreMiles);
// [11, 13, 15, 20];
8) .map | 배열의 각 요소에 제공된 함수를 실행 한 결과로 새 배열을 만듭니다.
let population = [200, 600, 170, 100];
let doublePopulation = population.map(element => element * 2);
// we are assigning the result of mapping to doublePopulation
// we would not be able to do this with the .forEach method
// because it returns undefined
console.log(doublePopulation);
// [400, 1200, 340, 200]
❗️ .forEach와 .map의 차이점은 .forEach 메소드를 호출하면 undefined를 반환하고 .map은 새 배열을 반환한다는 것입니다.
9) .reduce | 배열을 하나의 단일 값으로 결합하거나 줄입니다. reduce 방법을 배우는 간단한 방법은 배열의 모든 요소를 함께 추가하는 것입니다. 이 방법은 누산기와 전류 값의 두 매개 변수를 사용합니다.
let ticketPrices = [99.54, 56.43, 122.94];
let totalCostOfTickets = ticketPrices.reduce((total, amount) => total + amount)
// the accumulator is total; it's holding the new values as you add
// the amount is the next ticket price.
totalCostOfTickets = 278.91
10) .filter | 제공된 함수를 전달하는 요소를 사용하여 새 배열을 만듭니다.
let names = ["Rebecca", "Chris", "Ben", "Rachel"];
names = names.filter(name => name[0] === "R")
// this is looping through each name and checking if
// the first index of the string (aka first letter) is "R".
console.log(names):
// names = ["Rebecca", "Rachel"];
let ages = [16, 21, 26, 14];
ages = ages.filter(age => age >= 21)
// this is looping through each age and checking if
// the value is greater than or equal to 21.
console.log(ages):
// ages = [21, 26];
등록된 댓글이 없습니다.